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

查看:200
本文介绍了我可以在同一个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?

推荐答案

这是可能的。多捕获块的语法是:

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

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

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

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

另请注意,您不能同时捕获ExceptionA和ExceptionB如果ExceptionB是从ExceptionA直接或间接继承的,则阻止。编译器会抱怨:

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

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

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