我可以在同一个 catch 子句中捕获多个 Java 异常吗?

2022-08-31 04:04:52

在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();
}

有什么办法可以做到这一点吗?


答案 1

从Java 7开始,这已经成为可能。多捕获块的语法为:

try { 
  ...
} catch (IllegalArgumentException | SecurityException | IllegalAccessException |
            NoSuchFieldException e) { 
  someCode();
}

但请记住,如果所有异常都属于同一类层次结构,则只需捕获该基本异常类型即可。

另请注意,如果直接或间接地从 中继承,则无法在同一块中捕获两者。编译器将抱怨:ExceptionAExceptionBExceptionBExceptionA

Alternatives in a multi-catch statement cannot be related by subclassing
  Alternative ExceptionB is a subclass of alternative ExceptionA

解决此问题的方法是仅在例外列表中包含祖先异常,因为它还将捕获后代类型的异常。


答案 2

不完全是在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();
}