I need to catch two exceptions because they require the same handling logic. I would like to do something like:
catch (Exception e, ExtendsRuntimeException re) {
// common logic to handle both exceptions
}
Is it possible to avoid duplicating the handler code in each catch block?
Java 7 and later
Multiple-exception catches are supported, starting in Java 7.
The syntax is:
The static type of
exis the most specialized common supertype of the exceptions listed. There is a nice feature where if you rethrowexin the catch, the compiler knows that only one of the listed exceptions can be thrown.Java 6 and earlier
Prior to Java 7, there are ways to handle this, but they are inelegant and have limitations.
Approach #1
This gets messy if the exception handler needs to access local variables declared before the
try. And if the handler method needs to rethrow the exception (and it is checked) then you run into serious problems with the signature. Specifically,handleExceptionhas to be declared as throwingSuperException… which potentially means you have to change the signature of the enclosing method, and so on.Approach #2
Once again, we have a potential problem with signatures.
Approach #3
If you leave out the
elsepart (e.g. because there are no other subtypes ofSuperExceptionat the moment) the code becomes more fragile. If the exception hierarchy is reorganized, this handler without anelsemay end up silently eating exceptions.Note: if
SuperExceptionin the above isExceptionyou will either eat (all) unchecked exceptions or find that you are rethrowing an exception with the signatureException. Both of those things will be problematic.