[英]Specific Exceptions vs Exception
This may be a very dumb question, but I'm trying to understand why it is significant. 这可能是一个非常愚蠢的问题,但是我试图理解为什么它很重要。 Why is it important to use a specific exception instead of just using Exception. 为什么使用特定的异常而不是仅使用Exception如此重要。 Here is an example: 这是一个例子:
List<String> testList = new ArrayList<String>();
try {
testList.add(1, "String");
} catch (IndexOutOfBoundsException ex) {
ex.printStackTrace();
}
The above example has the specific exception this would raise. 上面的示例有特定的例外情况,这将引发此问题。 Why is it important to have IndexOutOFBoundsException
instead of just using Exception
. 为什么拥有IndexOutOFBoundsException
而不是仅使用Exception
为何很重要。 I know using Exception
with printStackTrace()
will show you what exception is really being raised. 我知道将Exception
与printStackTrace()
将向您显示真正引发了什么异常。
This is a good question, but it's also very a big question. 这是一个很好的问题,但这也是一个很大的问题。 In his famous book, Effective Java , Joshua Bloch dedicates an entire chapter to Exception best practices. 约书亚·布洛赫(Joshua Bloch)在其著名的著作《 有效的Java 》( Effective Java)中 ,整整一章专门介绍Exception最佳实践。 One of his recommendations that's relevant here is this: 他与此相关的建议之一是:
Use checked exceptions for recoverable conditions and runtime exceptions for programming errors. 将检查的异常用于可恢复的条件,将运行时异常用于编程错误。
The reason this is relevant to the code you posted is that by catching Exception you're ignoring the difference between "recoverable conditions" and "programming errors". 这与您发布的代码有关的原因是,通过捕获Exception,您将忽略“可恢复条件”和“编程错误”之间的区别。 You're saying, "I don't care what's wrong, I'm going to handle it." 您是在说:“我不在乎是怎么回事,我将处理它。”
While there is a time and place for this sort of handling, it's usually at the very highest level of your application. 尽管有时间和地点可以进行这种处理,但通常是在应用程序的最高级别。 For example, many web application frameworks display a nice-looking error page to the user in the case of an unhandled exception. 例如,在未处理的异常的情况下,许多Web应用程序框架向用户显示漂亮的错误页面。 They do this using some mechanism similar to catch Exception
to provide a nicer user experience and prevent the entire web application framework from crashing. 他们使用类似于catch Exception
某种机制来执行此操作,以提供更好的用户体验并防止整个Web应用程序框架崩溃。
On the other hand, if some careless developer were to catch Exception
somewhere in low level code, and then caught an exception he didn't mean to, there is a good chance the application would break in other ways, worsening the user experience and making debugging far more difficult. 另一方面,如果一些粗心的开发人员在低级代码中某个地方catch Exception
,然后捕获了一个他并非故意的异常,那么该应用程序很有可能会以其他方式破坏,从而恶化用户体验并导致调试困难得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.