Can I catch multiple Java exceptions in the same catch clause?
In Java, I want to do something like this:
try {
...
} catch (IllegalArgumentException, SecurityException,
IllegalAccessException, NoSuchFieldException e) {
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?
This is possible since Java 7. The syntax for try-catch block is:
try {
...
} catch (IOException | SQLException ex) {
...
}
Prior to Java 7 this was not possible. Remember though, if all the exceptions belong to the same class hierarchy, you can simply catch that base exception type. The only other way is to catch each exception in its own catch block.
Edit: Note that in Java 7, 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: The exception ExceptionB is already caught by the alternative ExceptionA
.
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();
}
在Java 7中,您可以定义多个catch子句,如:
catch (IllegalArgumentException | SecurityException e)
{
...
}
链接地址: http://www.djcxy.com/p/21128.html
上一篇: 尝试/ catch +使用,正确的语法