Michael Francis
Michael Francis

Reputation: 8747

Passing the type of exception to be caught

I'm building a little testing framework for my own code, and I'd like to be able to do this:

test.callTo(() -> {/*...*/}).doesThrow(SomeException.class);

or something like that.

The callTo method would just build an instance of a class which holds a java.lang.Runnable (or similar). That class will have a doesThrow method, which takes some parameter which represents the type of exception to be caught, and does this:

try {
    try {
        method.run();
    } catch(ThePassedInExceptionType e) {
        /* test passed */
        return;
    }
} catch (Throwable e) {}
/* test failed */

Is this type of thing possible? If so, how can it be done, and if not, what else could I do to ensure that my code throws the correct exceptions short of doing try/catch in my test code?

Upvotes: 0

Views: 40

Answers (2)

Andy Turner
Andy Turner

Reputation: 140309

I don't think you can do it directly, since the exception handling table is built at compile-time, and you don't know the expected exception type then.

However, you can probably do something like this, using reflection:

try {
  method.run();
} catch (Throwable t) {
  if (exceptionClass.isInstance(t)) {
    return; /* test passed */
  }
  throw t;  /* test failed; propagate error */
}

Upvotes: 1

Paul Boddington
Paul Boddington

Reputation: 37645

What you could do is pass a Class<? extends Exception>. Call this parameter clazz.

Then you could do

catch (Exception e) {
    if (clazz.isInstance(e)) 
        // do something
}

I'm not sure if this is good practice, but it should work.

Upvotes: 1

Related Questions