Catch a generic exception in Java?
- by Alex Baranosky
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?