This is not a question about exception handling in general, but it applies specifically end exclusively to the use of some frameworks. A few examples of typical starting points:
- GWT:
public void onFailure(Throwable caught)
implementation of theAsyncCallback
interface. - JAX-RS:
public Response toResponse(E throwable)
implementation of theExceptionMapper<E extends Throwable>
interface.
Both the above methods receive an instance of Throwable
. Normally, I've seen developers use a simple "if/else if" block to differentiate the handling logic:
// As specified by the AsyncCallback class of the GWT framework
public void onFailure(Throwable caught) {
if (caught instanceof AnException) {
// handle AnException
} else if (caught instanceof AnotherException) {
// handle AnotherException
} else if (caught instanceof YetAnotherException) {
// handle YetAnotherException
} else if (caught instanceof ...) {
// and so on...
}
}
Since I am not a fan of "if/else if" blocks for many reasons, I came up with the following "pattern" which converts the "if/else if" block into a "try/catch" block, behaving as if it were a "switch" block:
public void onFailure(Throwable caught) {
try {
throw caught;
} catch(AnException e1) {
// handle AnException
} catch(AnotherException e2) {
// handle AnotherException
} catch(YetAnotherException e3) {
// handle YetAnotherException
} catch(...) {
// and so on...
}
}
My question is: Are there any drawbacks - in terms of performance, best practices, code readability, general safety, or just anything else I'm not considering or noticing - using this approach?