Exceptions
An exception in Groovy is a Java exception: the classes are the ones of java.lang, throw takes any Throwable, and the statement is try, catch, finally. The Java course covers the hierarchy; this lesson is the Groovy shape.
Catch and finally
catch.groovy
def parse(String text) {
def value = -1
try {
value = Integer.parseInt(text)
} catch (NumberFormatException error) {
println "not a number: ${error.message}"
} finally {
println 'attempt finished'
}
value
}
println parse('42')
println parse('forty-two')
groovy catch.groovy
attempt finished
42
not a number: For input string: "forty-two"
attempt finished
-1
finally runs whether the try succeeded or failed, which is where a resource is closed. A catch block may name several unrelated types with |:
multicatch.groovy
def check(String text) {
def result = 'none'
try {
result = Integer.parseInt(text).toString()
} catch (NumberFormatException | ArithmeticException error) {
println "caught ${error.getClass().simpleName}"
}
result
}
println check('42')
println check('forty-two')
groovy multicatch.groovy
42
caught NumberFormatException
none
A multi-catch is one block for several types, and the variable is typed as their common superclass of RuntimeException. The alternatives must not be subclasses of one another, because the first would always answer.
An exception of your own
custom.groovy
class InsufficientFunds extends RuntimeException {
BigDecimal missing
InsufficientFunds(String message, BigDecimal missing) {
super(message)
this.missing = missing
}
static BigDecimal withdraw(BigDecimal balance, BigDecimal amount) {
if (amount > balance) {
throw new InsufficientFunds('not enough money', amount - balance)
}
balance - amount
}
static void main(String[] args) {
try {
println withdraw(100.00, 25.00)
println withdraw(10.00, 25.00)
} catch (InsufficientFunds error) {
println error.message
println "missing: ${error.missing}"
}
}
}
groovy custom.groovy
75.00
not enough money
missing: 15.00
A custom exception is a class with a constructor, and the extra field travels with it. An unchecked parent (RuntimeException) needs no throws clause, which is why a Groovy script rarely writes one. The class carries its own main, because a script body cannot share a file with a class of the same name as the file.
The trace of an uncaught exception
An exception nobody catches ends the script. The launcher prints Caught:, the exception, and the frames that led to it, and the exit status is 1:
uncaught.groovy
def divide(int a, int b) {
a / b
}
println divide(10, 2)
println divide(1, 0)
groovy uncaught.groovy
5
Caught: java.lang.ArithmeticException: Division by zero
java.lang.ArithmeticException: Division by zero
at uncaught.divide(uncaught.groovy:2)
at uncaught.run(uncaught.groovy:6)
exit status: 1
The first line of the trace names the type and the message; the first frame names the line that threw. The Groovy errors page collects the messages a beginner meets, from a missing method to a class that cannot be cast.
Related
- Groovy errors: the messages and their causes.
- The power assert: the AssertionError a test raises.
- Classes, properties and fields: the class of the custom exception.
Article author: Arthur Isaev