问题

在Java中,我想做这样的事情:

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

...代替:

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

有没有办法做到这一点?


#1 热门回答(909 赞)

这是可能的887646256。 try-catch块的语法是:

try { 
  ...
} catch (IOException | SQLException ex) { 
  ...
}

在Java 7之前,这是不可能的。但请记住,如果所有异常都属于同一个类层次结构,则可以简单地捕获该基本异常类型。唯一的另一种方法是在自己的catch块中捕获每个异常。

编辑:请注意,在Java 7中,如果ExceptionB直接或间接地从ExceptionA继承,则无法在同一块中捕获ExceptionA和ExceptionB。编译器会抱怨:The exception ExceptionB is already caught by the alternative ExceptionA


#2 热门回答(98 赞)

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

#3 热门回答(22 赞)

在Java 7中,你可以定义多个catch子句,如:

catch (IllegalArgumentException | SecurityException e)
{
    ...
}

原文链接