In Java, I want to do something like this:
try {
...
} catch (/* code to catch IllegalArgumentException, SecurityException,
IllegalAccessException, and NoSuchFieldException at the same time */) {
someCode();
}
…instead of:
try {
...
} catch (IllegalArgumentException e) {
someCode();
} catch (SecurityException e) {
someCode();
} catch (IllegalAccessException e) {
someCode();
} catch (NoSuchFieldException e) {
someCode();
}
Is there any way to do this?
Best Answer
This has been possible since Java 7. The syntax for a multi-catch block is:
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
andExceptionB
in the same block ifExceptionB
is inherited, either directly or indirectly, fromExceptionA
. The compiler will complain: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.