Reputation: 126
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.
Upvotes: 0
Views: 2593
Reputation:
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.
Upvotes: 4