捕获Exception类而不是Exception子类是不好的做法? [英] Is it bad practice to catch the Exception class instead of Exception sub-classes?

查看:456
本文介绍了捕获Exception类而不是Exception子类是不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抛出Exception子类的方法。如果我为Exception的每个子类执行相同的catch功能,那么只是捕获E​​xceptions类或者我应该单独捕获每个异常是不好的做法吗?

I have a method which throws subclasses of Exception. If I am performing the same catch functionality for each sub-class of Exception that's causght is it bad practice to just catch the Exceptions class or should I catch each exception individually ?

推荐答案

是的,这是不好的做法,因为它会使catch块捕获不应被捕获的运行时异常。

Yes, it's bad practice, because it makes the catch block catch runtime exceptions that shouldn't be caught.

如果你使用Java 7,你可以使用

If you use Java 7, you can use

catch (SomeException | SomeOtherException | YetAnotherException e) {
    ...
}

这篇关于捕获Exception类而不是Exception子类是不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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