I know the overhead of Java exceptions has been done to death on SO, but I didn't find anything that addressed my situation. I have a Future, which upon calling get() might throw an ExecutionException containing any number of application-specific exceptions. I was wondering whether there is significant overhead using the nicer-looking try-catch block instead of the ugly if-instanceof-then-cast pattern. For example, it might look something like this:
private Response handleException(ExecutionException e) throws MyApplicationException {
try {
throw e.getCause();
} catch (ApplicationException1 e1) {
// known error
throw MyApplicationException.convert(e1);
} catch (ApplicationException2 e2) {
// create error response
return new Response(e2);
} catch (Throwable t) {
// unknown error
throw new RuntimeException(t);
}
}
private Response handleException2(ExecutionException e) throws MyApplicationException {
Throwable cause = e.getCause();
if (cause instanceof ApplicationException1) {
ApplicationException1 e1 = (ApplicationException1) cause;
throw MyApplicationException.convert(e1);
} else if (cause instanceof ApplicationException2) {
ApplicationException2 e2 = (ApplicationException2) cause;
return new Response(e2);
} else {
throw new RuntimeException(cause);
}
}
My theory is that there shouldn't be a huge amount of overhead since
- The exception and stack trace have already been constructed.
- I am performing reflection on the exception object in both methods anyway.
- The exception is caught immediately and never propagated.