Ok I know catching throwable is not a good idea:
try { // Some code } catch(Throwable e) { // Not cool! // handle the exception }
But recently I was reading through an open sourced code and I saw this interesting (at least to me) piece of code:
try { // Some Code } catch (Throwable ex){ response = handleException(ex, resource); } private handleException(Throwable t, String resource) { if (t instanceof SQLEXception) { // Some code } else if (t instanceof IllegalArgumentException) { //some code } //so on and so forth }
This doesn't seem to be that bad? What is wrong with this approach?
Catching Throwable This means that the calling code is reacting to recoverable and irrecoverable situations in the same way. The general rule in handling exceptions is that the try-catch block must be as specific as possible in catching exceptions. That is, a catch-all scenario must be avoided.
Catching Specific Exceptions in PythonA try clause can have any number of except clauses to handle different exceptions, however, only one will be executed in case an exception occurs. We can use a tuple of values to specify multiple exceptions in an except clause.
Don't Catch Throwable Throwable is the superclass of all exceptions and errors. You can use it in a catch clause, but you should never do it! If you use Throwable in a catch clause, it will not only catch all exceptions; it will also catch all errors.
Context for this answer: Throwable includes both Error and Exception as subclasses, so first try/catch is inclusive of second but usually over-broad. It also includes user-defined direct subclasses of Throwable and instances of Throwable itself.
There are various reasons why you should not catch a Throwable. First of all is, that Throwable
includes Error
s - and there's normally not much an application can do if one of these appears. Also Throwable reduces your chances of finding out, WHAT has happened. All you get is "something bad has happened" - which might be a catastrophe or just a nuisance.
The other aproach is better but of course I still would not catch Throwable, but try to catch more specific Exceptions, if possible at all. Otherwise you are catching everything and then try to sort out which kind of bad thing happened. Your example could be written as...
try { ... } catch (SQLEXception ex){ response = ... ; } catch (IllegalArgumentException ex){ response = ...; }
...which would reduce the amount of if ( ... instanceof ... )
blocks (which are only needed because the author first decided to catch everything in one big bucket). It something actually throws Throwable
, then you don't have much choice, of course.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With