Is it a bad practice to catch Throwable? Is it a bad practice to catch Throwable? java java

Is it a bad practice to catch Throwable?


You need to be as specific as possible. Otherwise unforeseen bugs might creep away this way.

Besides, Throwable covers Error as well and that's usually no point of return. You don't want to catch/handle that, you want your program to die immediately so that you can fix it properly.


This is a bad idea. In fact, even catching Exception is usually a bad idea. Let's consider an example:

try {    inputNumber = NumberFormat.getInstance().formatNumber( getUserInput() );} catch(Throwable e) {    inputNumber = 10; //Default, user did not enter valid number}

Now, let's say that getUserInput() blocks for a while, and another thread stops your thread in the worst possible way ( it calls thread.stop() ). Your catch block will catch a ThreadDeath Error. This is super bad. The behavior of your code after catching that Exception is largely undefined.

A similar problem occurs with catching Exception. Maybe getUserInput() failed because of an InterruptException, or a permission denied exception while trying to log the results, or all sorts of other failures. You have no idea what went wrong, as because of that, you also have no idea how to fix the problem.

You have three better options:

1 -- Catch exactly the Exception(s) you know how to handle:

try {    inputNumber = NumberFormat.getInstance().formatNumber( getUserInput() );} catch(ParseException e) {    inputNumber = 10; //Default, user did not enter valid number}

2 -- Rethrow any exception you run into and don't know how to handle:

try {    doSomethingMysterious();} catch(Exception e) {    log.error("Oh man, something bad and mysterious happened",e);    throw e;}

3 -- Use a finally block so you don't have to remember to rethrow:

 Resources r = null; try {      r = allocateSomeResources();      doSomething(r); } finally {     if(r!=null) cleanUpResources(r); }


Also be aware that when you catch Throwable, you can also catch InterruptedException which requires a special treatment. See Dealing with InterruptedException for more details.

If you only want to catch unchecked exceptions, you might also consider this pattern

try {   ...} catch (RuntimeException exception) {  //do something} catch (Error error) {  //do something}

This way, when you modify your code and add a method call that can throw a checked exception, the compiler will remind you of that and then you can decide what to do for this case.