I'm trying to define a method like the following:
static def myMethod(expectedExceptionType, Closure closure) {
try {
closure()
} catch (expectedExceptionType e) {
println "Threw an exception: ${e.getMessage()}"
}
}
and run it with something like this:
MyClass.myMethod(NullPointerException) {
doSomeStuff()
}
I basically want to be able to pass in a type to my method and then use that actual parameter to define the formal parameter's type in the catch block of my method.
Is this possible?
One thing you can do is catch Exception and check if the caught exception is an instance of your expected exception and do stuff. But then the question is each exception will be thrown for different reasons and you can't have the same handling code for different exceptions. If you do, why catch the specific one at all?