You are right when you say that catching Throwable
is not a good idea. However, the code that you present in your question is not catching Throwable
in an evil way but let's talk about that later. For now, the code that you present in your question has several advantages :
1. Readability
If you look at the code carefully, you will notice that even though the catch block is catching a Throwable
, the handleException
method is checking the type of exception thrown and possibly taking different actions based on the exception type.
The code presented in your question is synonymous to saying:
try {
doSomething();
} catch (SQLEXception ex){
response = handleException(resource);
} catch(IllegalArgumentException ex) {
response = handleException(resource);
} catch(Throwable ex) {
response = handleException(resource);
}
Even if you have to catch 10+ exceptions only, this code can easily take up a lot of lines of code and the multi-catch construct is not going to make the code any cleaner. The code that you present in your question is simply delegating the catch
to another method to make the actual method that does the work more readable.
2. Reusability
The code for the handleRequest method could easily be modified and placed in a utility class and accessed throughout your application to handle both Exception
s and Error
s. You could even extract the method into two private
methods; One that handles Exception
and one that handles Error
and have the handleException
method that takes a Throwable
further delegate the calls to these methods.
3. Maintainibility
If you decide that you want to change the way you log an SQLException
s in your application, you have to make this change in a single place rather than visiting every method in every class that throws an SQLException
.
So is catching Throwable
a bad idea?
The code that you present in your question is not really the same as catching Throwable
alone. The following piece of code is a big no-no:
try {
doSomething();
} catch(Throwable e) {
//log, rethrow or take some action
}
You should catch Throwable
or Exception
as far away in the catch
chain as possible.
Last but not the least, remember that the code you present in your question is framework's code and there are certain errors that the framework can still recover from. See When to catch java.lang.Error for a better explanation.
Throwable
. It still isn't a good idea in application-level code, unless you want to have some kind of "handler of last resort".