Saturday, March 1, 2014

Why Catching Throwable or Error is bad?

We often hear advice that catching Throwable or Error is bad practice and Java developer should avoid catching these, but have you thought Why? If language allows you to catch anything which is instance of java.lang.Throwable, then what is the problem of catching them or their subclass java.lang.Error? If they are bad, shouldn't Java itself has prohibited them from catching? Well this all looks good on theory, but not in real world programming. As I said before in Java Exception best practices post, Ideally you should never catch Throwable or in particular Error. There are several reasons why catching instance of java.lang.Throwable is bad idea, because in order to catch them you have to declare at your method signature e.g. public void doSomething() throws Throwable. When you do this, no body knows what kind of Error this method is going to throw, and until you know what is the problem, how can you resolve that. Main purpose of providing Exception handling mechanism is to handle error situation properly, but you can't a provide a solution which can solve all problems. That's why we have specific Exception classes e.g. FileNotFoundException, IllegalArgumentException, IOException and so on. So if you don't know how to resolve or handle error, there is no point catching Throwable, all it make your code hard to read and comprehend. Remember, each error handling code is driven by business/audit/reporting or quality requirement and catching Throwable just obscure those logics.

Some programmer catch Throwable and re-throw it by wrapping it into RuntimeException. Catching and re-throwing Exception after logging is OK but you must not rewrap the exception in a RuntimeException, and if you do make sure to preserve actual cause and stack-trace. Spring framework does lot of this checked to unchecked exception conversion, which makes your code free of boiler-plate but also posses challenge when you are going to debug any problem. When Spring framework prints stack trace for any issue, they are usually very long, combination of multiple exception and their cause, which actually buries the real issue down in the log file. If you are not careful, you may spend countless hours fixing bug at wrong place.

Read more here

Leave a Reply

All Tech News IN © 2011 & Main Blogger .