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

有什么办法吗?


当前回答

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

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

其他回答

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

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

在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.
  }

非常简单:

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

如果存在异常的层次结构,则可以使用基类来捕获异常的所有子类。在退化情况下,您可以通过以下方式捕获所有Java异常:

try {
   ...
} catch (Exception e) {
   someCode();
}

在更常见的情况下,如果RepositoryException是基类,PathNotFoundException是派生类,则:

try {
   ...
} catch (RepositoryException re) {
   someCode();
} catch (Exception e) {
   someCode();
}

上述代码将捕获一种异常处理的RepositoryException和PathNotFoundException,所有其他异常都集中在一起。从Java 7开始,根据@OscarRyz的上述回答:

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

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

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