Reputation: 148
I would like to catch an exception I expect but allow the others through.
The solution I have come to at the moment is:
protected void perfromCall(Class expectedException) throws Exception {
try {
response = call.call(request);
} catch (Exception e) {
if (!expectedException.isInstance(e)) {
throw new Exception(e);
}
}
}
While this will silently eat the expected exception as I would like and throw the others, what I don't like about it is that it wraps the unexpected exceptions and now I have to catch unexpected in the caller whereas previously (before trying to silently catch expected exceptions) I could let them bubble up to the test framework to fail the test.
Is there a cleaner way to say "I expected exceptions of class A, but for any other exception, let it be thrown up the chain until it's handled by the test framework above"?
Edit: I wanted to provide some justification as to why I want to do this as there were some answers (now deleted) that questioned silently eating an exception. This is for a test framework that calls a service. Some of the tests pass bad arguments to the service, so they expect an exception thrown by the service due to catching the invalid request. I therefore want to silently eat the expected exception, but still let unexpected exceptions to bubble up and fail the test.
Upvotes: 1
Views: 1356
Reputation: 100196
protected void perfromCall(Class<?> expectedException) throws Exception {
try {
response = call.call(request);
} catch (Exception e) {
if (!expectedException.isInstance(e)) {
throw e;
}
}
}
Upvotes: 8