Alex Baranosky Alex Baranosky - 1 year ago 80
Java Question

Catch a generic exception in Java?

We use JUnit 3 at work and there is no

annotation. I wanted to add a utility to our code to wrap this:

try {
fail("some error message");
} catch (SomeSpecificExceptionType ex) {

So I tried this:

public static class ExpectedExceptionUtility {
public static <T extends Exception> void checkForExpectedException(String message, ExpectedExceptionBlock<T> block) {
try {
} catch (T ex) {

However, Java cannot use generic exception types in a catch block, I think.

How can I do something like this, working around the Java limitation?

Is there a way to check that the
variable is of type

Answer Source

You could pass the Class object in and check that programatically.

public static <T extends Exception> void checkForException(String message, 
        Class<T> exceptionType, ExpectedExceptionBlock<T> block) {
    try {
   } catch (Exception ex) {
       if ( exceptionType.isInstance(ex) ) {
       } else {
          throw ex;  //optional?

checkForException("Expected an NPE", NullPointerException.class, //...

I'm not sure if you'd want the rethrow or not; rethrowing would equally fail/error the test but semantically I wouldn't, since it basically means "we didn't get the exception we expected" and so that represents a programming error, instead of a test environment error.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download