Besides the obvious case of treating different exceptions differently, is there any benefit in treating exceptions separately? I see a lot of code that looks something among the lines of:
try {
doSomethingThatMayThrowExceptions();
} catch (SomeException e) {
} catch (OtherException e) {
}
I always tend to just catch the generic Exception when I only have one exception-handling process.
A derived question would be: is it better in any way to state the exact type of exception you are catching, if it’s just one? For example:
try {
number = Integer.parseInt(numberString);
} catch (Exception e) {
// ...
}
In the above example, the try block can only throw a NumberFormatException. Is there any downside to catching the generic Exception here?
Not really. But it can be asked, what do you achieve by “hiding” the exact exception?
If you catch
NumberFormatException, you can instantly see which exceptions are expected to be thrown.EDIT: Pardon me. The above example can also throw unchecked exceptions ie. NPEs, so you’re actually catching more exceptions and treating them all the same way. You might actually want to implement different exception handling for those exceptions (if you even want to catch and handle unchecked exceptions).