在Java中是否可以在同一catch块中捕获两个异常? [英] Is it possible in Java to catch two exceptions in the same catch block?

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

问题描述

我需要捕获两个异常,因为它们需要相同的处理逻辑。我想做类似的事情:

I need to catch two exceptions because they require the same handling logic. I would like to do something like:

catch (Exception e, ExtendsRuntimeException re) {
    // common logic to handle both exceptions
}

是否有可能避免在每个catch块中重复处理程序代码?

Is it possible to avoid duplicating the handler code in each catch block?

推荐答案

Java 7及更高版本



从Java 7开始,支持多个异常捕获

语法为:

try {
     // stuff
} catch (Exception1 | Exception2 ex) {
     // Handle both exceptions
}

ex 的静态类型是列出的异常中最特殊的通用超类型。有一个很好的功能,如果您在捕获中重新抛出 ex ,则编译器知道只能抛出列出的异常之一。

The static type of ex is the most specialized common supertype of the exceptions listed. There is a nice feature where if you rethrow ex in the catch, the compiler knows that only one of the listed exceptions can be thrown.

在Java 7之前,有多种方法可以解决此问题,但是

Prior to Java 7, there are ways to handle this problem, but they tend to be inelegant, and to have limitations.

try {
     // stuff
} catch (Exception1 ex) {
     handleException(ex);
} catch (Exception2 ex) {
     handleException(ex);
}

public void handleException(SuperException ex) {
     // handle exception here
}

如果异常处理程序需要访问在 try 之前声明的局部变量,这将变得很混乱。而且,如果处理程序方法需要重新引发异常(并进行了检查),则签名会遇到严重问题。具体来说,必须将 handleException 声明为抛出 SuperException ...,这可能意味着您必须更改代码的签名。

This gets messy if the exception handler needs to access local variables declared before the try. And if the handler method needs to rethrow the exception (and it is checked) then you run into serious problems with the signature. Specifically, handleException has to be declared as throwing SuperException ... which potentially means you have to change the signature of the enclosing method, and so on.

try {
     // stuff
} catch (SuperException ex) {
     if (ex instanceof Exception1 || ex instanceof Exception2) {
         // handle exception
     } else {
         throw ex;
     }
}

再次,我们在签名方面存在潜在的问题。

Once again, we have a potential problem with signatures.

try {
     // stuff
} catch (SuperException ex) {
     if (ex instanceof Exception1 || ex instanceof Exception2) {
         // handle exception
     }
}

如果省略了 else 部分(例如,因为存在目前没有 SuperException 的其他子类型),代码变得更加脆弱。如果重组了异常层次结构,则没有 else 的此处理程序可能最终会悄悄地吞噬异常!

If you leave out the else part (e.g. because there are no other subtypes of SuperException at the moment) the code becomes more fragile. If the exception hierarchy is reorganized, this handler without an else may end up silently eating exceptions!

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

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