Catch a generic exception in Java?

Posted by Alex Baranosky on Stack Overflow See other posts from Stack Overflow or by Alex Baranosky
Published on 2010-06-11T16:54:32Z Indexed on 2010/06/11 17:02 UTC
Read the original article Hit count: 144

Filed under:
|
|

We use JUnit 3 at work and there is no ExpectedException annotation. I wanted to add a utility to our code to wrap this:

 try {
     someCode();
     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 {
        block.exceptionThrowingCode();
        fail(message);
    } 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 ex variable is of type T?

© Stack Overflow or respective owner

Related posts about java

Related posts about generics