0

I am always using catch (Exception e) {//whatever} but is that actually correct ? Why should I use specific exceptions if general Exception works for everything ? Does it somehow affect the performance ?

1
  • 2
    There's no performance difference, but in the case of specific exceptions, you can handle them specifically to recover from the error. If you're just catching Exception, then the best you can do is print its stack trace. But if, for example, you're building an ATM/Banking app, you could catch an InsufficientFundsException and treat it differently than say, InvalidPinException. Commented Nov 1, 2015 at 20:19

1 Answer 1

4

I am always using catch (Exception e) {//whatever} but is that actually correct ?

No. That goes against good recommendation to catch the most appropriate specific exception.

Why should I use specific exceptions if general Exception works for everything ?

Because exceptions you don't really expect can be masked. For example, when performing some database operations, a SQLException might happen, which is expected, and you can implement handling it gracefully. And if a ArrayIndexOutOfBoundsException gets thrown, that would be unexpected, and most probably indicate a programming error. But if instead SQLException you catch Exception, then you might never know that the unexpected ArrayIndexOutOfBoundsException was thrown. And the graceful cleanup might also not apply for this kind of exception.

Using specific exceptions also makes the code more readable: the reader can understand what kind of things can go wrong in the code guarded by the try-catch.

Related to this is that when you declare a method to throw an exception, the declaration should use the exception that's most appropriate to the abstraction.

Does it somehow affect the performance ?

Not at all.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.