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 Answer
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.
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 anInsufficientFundsExceptionand treat it differently than say,InvalidPinException.