When things go wrong
A Java exception becomes a Ring error. Catch it with try, ask for the exception object, and validate before the call.
What you will learn#
try ... catcharound a Java call,jLastException()and the class of the exception,- null values and
jIsNull(), - a Ring error inside a callback.
The program#
# Tutorial 7: when things go wrong - Java exceptions become Ring errors
load "java.ring"
using {
"java.lang"
"java.io"
"java.util"
}
# a Java exception stops the program, unless the call is inside try ... catch
try
? Integer.parseInt("12x")
catch
? "caught: " + str2list(cCatchError)[1]
done
# the exception is an object too: jLastException() gives it
try
new FileReader("/this/file/does/not/exist.txt")
catch
oError = jLastException()
? oError.getClass().getName()
? oError.getMessage()
done
# an error in the index of a list
oList = new ArrayList(["a","b"])
try
? oList.@get(5)
catch
? jLastException().getClass().getSimpleName()
done
# null: a Java method that gives null gives an object that jIsNull() recognises
oMap = new HashMap
? jIsNull(oMap.@get("missing"))
# validate before the call, and finish with a final step
try
? divide(10,0)
catch
? cCatchError
done
# a Ring error inside a callback reaches Java as an exception, and then the Ring try
try
oList.sort("raise('the comparator failed')")
catch
? "the callback failed: " + (substr(cCatchError,"the comparator failed") > 0)
done
# test the class of the exception
try
Integer.parseInt("x")
catch
oEx = jLastException()
? jInstanceOf(oEx,"java.lang.IllegalArgumentException") # NumberFormatException is an IllegalArgumentException
done
func divide nA, nB
if nB = 0
raise("divide: the second number is 0")
ok
return nA / nBcaught: Java Exception: java.lang.NumberFormatException: For input string: "12x"
java.io.FileNotFoundException
\this\file\does\not\exist.txt (The system cannot find the path specified)
IndexOutOfBoundsException
1
divide: the second number is 0
the callback failed: 1
1How it works#
When a Java method throws, the Ring program stops with the text of the exception, unless the call is inside try. jLastException() returns the exception as an object: ask for getClass().getName() or getMessage(). A method that returns null gives a value that jIsNull() recognises.
Exercises#
- Parse
"12x"withInteger.parseIntand print a friendly message. - Open a file that does not exist and print the exception class.
- Write a function that returns a default when the exception happens.