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.