在 Java 中,我想做这样的事情:
try {
...
} catch (/* code to catch IllegalArgumentException, SecurityException,
IllegalAccessException, and NoSuchFieldException at the same time */) {
someCode();
}
... 代替:
try {
...
} catch (IllegalArgumentException e) {
someCode();
} catch (SecurityException e) {
someCode();
} catch (IllegalAccessException e) {
someCode();
} catch (NoSuchFieldException e) {
someCode();
}
有什么办法吗?
从 Java 7开始,这已经成为可能。多捕获块的语法为:
try {
...
} catch (IllegalArgumentException | SecurityException | IllegalAccessException |
NoSuchFieldException e) {
someCode();
}
但是请记住,如果所有异常都属于同一类层次结构,则可以简单地捕获该基本异常类型。
还要注意的是,你不能赶上既ExceptionA
和ExceptionB
在同一个块,如果ExceptionB
是继承,直接或间接地从ExceptionA
。编译器会抱怨:
Alternatives in a multi-catch statement cannot be related by subclassing
Alternative ExceptionB is a subclass of alternative ExceptionA
解决此问题的方法是仅将祖先异常包括在异常列表中,因为它还会捕获后代类型的异常。
不完全是在 Java 7 之前,但我会做这样的事情:
Java 6 及更低版本
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)
{
...
}