我可以在同一个 catch 子句中捕获多个 Java 异常吗? [英] Can I catch multiple Java exceptions in the same catch clause?

查看:28
本文介绍了我可以在同一个 catch 子句中捕获多个 Java 异常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Java, I want to do something like this:

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

有没有办法做到这一点?

Is there any way to do this?

推荐答案

这已经成为可能 自 Java 7.multi-catch 块的语法是:

This has been possible since Java 7. The syntax for a multi-catch block is:

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

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

Remember, though, that if all the exceptions belong to the same class hierarchy, you can simply catch that base exception type.

另请注意,如果 ExceptionB 直接或间接地从 ExceptionAExceptionB代码>异常A.编译器会抱怨:

Also note that you cannot catch both ExceptionA and ExceptionB in the same block if ExceptionB is inherited, either directly or indirectly, from ExceptionA. The compiler will complain:

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

解决这个问题的方法是只在异常列表中包含祖先异常,因为它也会捕获后代类型的异常.

The fix for this is to only include the ancestor exception in the exception list, as it will also catch exceptions of the descendant type.

这篇关于我可以在同一个 catch 子句中捕获多个 Java 异常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆