简体   繁体   English

在Java中对catch块中的OR进行异常处理是一个好主意吗?

[英]Is it a good idea in Java to OR exceptions in catch block?

Should we OR exceptions like this ? 我们应该OR这样的例外吗?

catch (final CustomExceptionA | CustomExceptionB e) {

       Should we catch expections like this ? 
    }

It's a fine way to do it if you want to handle them in the exact same way. 如果您要以完全相同的方式处理它们,这是一个很好的方法。 It'll also only compile on Java 7 (and above). 它还将仅在Java 7(及更高版本)上编译。

In Java versions before 7 there was always the issue that if you had to catch multiple exceptions, but (iE) only needed to log them, you had to duplicate a lot of code. 在Java 7之前的版本中,始终存在一个问题,如果必须捕获多个异常,但是(iE)仅需要记录它们,则必须重复很多代码。 Example Java 6: 示例Java 6:

} catch (NullpointerException e) {
  log(e);
} catch (ArrayIndexOutOfBoundsException e) {
  log(e);
} catch (NumberFormatException e) {
...

In Java 7 you can use the | 在Java 7中,可以使用|。 operator to simplify this and - the important part - only have to write the error-handling code once, which will avoid common bugs like copy & paste or similar. 操作员可以简化此操作,并且-重要的部分-只需编写一次错误处理代码,就可以避免常见的错误,例如复制和粘贴或类似错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM