Groovy Exception handling (try, catch, Exception)
def div(a, b) {
return a/b
}
if (args.size() < 2) {
println("You need to pass two numbers")
System.exit(1)
}
def res = div(args[0] as Integer, args[1] as Integer)
println(res)
It works well if the division work well, but:
$ groovy divide.groovy 3 0
Caught: java.lang.ArithmeticException: Division by zero
java.lang.ArithmeticException: Division by zero
at divide.div(divide.groovy:2)
at divide.run(divide.groovy:13)
We can use try
and catch
to catch the exception:
def div(a, b) {
return a/b
}
if (args.size() < 2) {
println("You need to pass two numbers")
System.exit(1)
}
try {
def res = div(args[0] as Integer, args[1] as Integer)
println(res)
} catch(Exception e) {
println("Exception: ${e}")
}
timestamp: 2019-04-21T15:30:01 tags:
- try
- catch
- Exception