Can I catch multiple Java exceptions in the same catch clause?
This has been possible since Java 7. The syntax for a multi-catch block is:
try {
...
} catch (IllegalArgumentException | SecurityException | IllegalAccessException |
NoSuchFieldException e) {
someCode();
}
Remember, though, that if all the exceptions belong to the same class hierarchy, you can simply catch that base exception type.
Also note that you cannot catch both ExceptionA
and ExceptionB
in the same block if ExceptionB
is inherited, either directly or indirectly, from ExceptionA
. The compiler will complain:
Alternatives in a multi-catch statement cannot be related by subclassing
Alternative ExceptionB is a subclass of alternative ExceptionA
The fix for this is to only include the ancestor exception in the exception list, as it will also catch exceptions of the descendant type.
No, one per customer prior to Java 7.
You can catch a superclass, like java.lang.Exception, as long as you take the same action in all cases.
try {
// some code
} catch(Exception e) { //All exceptions are caught here as all are inheriting java.lang.Exception
e.printStackTrace();
}
But that might not be the best practice. You should only catch an exception when you have a strategy for actually handling it - and logging and rethrowing is not "handling it". If you don't have a corrective action, better to add it to the method signature and let it bubble up to someone that can handle the situation.
With JDK 7 and later you can do this:
try {
...
} catch (IllegalArgumentException | SecurityException | IllegalAccessException | NoSuchFieldException e) {
someCode();
}
Not exactly before Java 7 but, I would do something like this:
Java 6 and before
try {
//.....
} catch (Exception exc) {
if (exc instanceof IllegalArgumentException || exc instanceof SecurityException ||
exc instanceof IllegalAccessException || exc instanceof NoSuchFieldException ) {
someCode();
} else if (exc instanceof RuntimeException) {
throw (RuntimeException) exc;
} else {
throw new RuntimeException(exc);
}
}
Java 7
try {
//.....
} catch ( IllegalArgumentException | SecurityException |
IllegalAccessException |NoSuchFieldException exc) {
someCode();
}