How can I set the the expected Exception type for a catch statement with a parameter I've passed into a method?

441 views Asked by At

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?

3

There are 3 answers

0
Praba On

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?

2
ataylor On

That is not possible. While groovy allows dynamic typing in many situations, it doesn't in the case of exception handling. Groovy, like Java, needs a concrete exception type at compile time to build the exception table in the class file.

As suggested by prabugp, you can handle this at runtime by catching all exceptions and testing them with the Class.isAssignableFrom() method. For example:

static def myMethod(expectedExceptionType, Closure closure) {
    try {
        closure()
    } catch (e) {
        if (expectedExceptionType.isAssignableFrom(e.class)) {
            println "Threw an exception: ${e.getMessage()}"
        } else {
            throw e
        }
    }
}
0
blackdrag On

A Java based solution can be found in GroovyAssert#shouldFail. The Groovy version of this would not look all that much different. But I would suggest just to use that class, since it is part of the Groovy distribution anyway