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

有什么办法吗?


当前回答

在pre-7中,如何:

  Boolean   caught = true;
  Exception e;
  try {
     ...
     caught = false;
  } catch (TransformerException te) {
     e = te;
  } catch (SocketException se) {
     e = se;
  } catch (IOException ie) {
     e = ie;
  }
  if (caught) {
     someCode(); // You can reference Exception e here.
  }

其他回答

自Java7以来,这是可能的。多捕获块的语法为:

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

不过,请记住,如果所有异常都属于同一个类层次结构,则可以简单地捕获该基本异常类型。

还要注意,如果ExceptionB直接或间接从ExceptionA继承,则无法在同一块中捕获ExceptionA和ExceptionB。编译器会抱怨:

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

解决方法是只在异常列表中包含祖先异常,因为它还会捕获后代类型的异常。

在Java7中,您可以定义多个catch子句,如:

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

捕获恰好是异常层次结构中父类的异常。这当然是不好的做法。在您的案例中,常见的父异常恰好是exception类,捕获任何作为exception实例的异常确实是错误的做法-像NullPointerException这样的异常通常是编程错误,通常应该通过检查空值来解决。

非常简单:

try { 
  // Your code here.
} catch (IllegalArgumentException | SecurityException | IllegalAccessException |
            NoSuchFieldException e) { 
  // Handle exception here.
}

对于kotlin来说,目前还不可能,但他们已经考虑添加:来源但现在,只需要一个小技巧:

try {
    // code
} catch(ex:Exception) {
    when(ex) {
        is SomeException,
        is AnotherException -> {
            // handle
        }
        else -> throw ex
    }
}