Friday, February 28, 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.
Read more �

No comments:

Post a Comment