简体   繁体   中英

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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