Specific Exceptions vs Exception

天大地大妈咪最大 提交于 2019-12-25 06:57:59

问题


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. 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. I know using Exception with printStackTrace() will show you what exception is really being raised.


回答1:


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. 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". 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. 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.

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.

See also

  • Effective Java, Second Edition, by Joshua Bloch
    • Item 58: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors
    • Item 61: Throw exceptions appropriate to the abstraction [which also implies to catch exceptions appropriate to the abstraction]
    • Item 65: Don't ignore exceptions [catching Exception is like ignoring a whole class of possible errors]


来源:https://stackoverflow.com/questions/36926285/specific-exceptions-vs-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!