Search This Blog

Saturday, March 22, 2008

Why is it not advisable to catch type “Exception”?

Exception handling in Java is polymorphic in nature. For example if you catch type Exception in your code then it can catch or throw its descendent types like IOException as well. So if you catch the type Exception before the type IOException then the type Exception block will catch the entire exceptions and type IOException block is never reached. In order to catch the type IOException and handle it differently to type Exception, IOException should be caught first (remember that you can’t have a bigger basket above a smaller basket). The diagram below is an example for illustration only. In practice it is not recommended to catch type “Exception”. We should only catch specific subtypes of the Exception class. Having a bigger basket (i.e. Exception) will hide or cause problems. Since the RunTimeException is a subtype of Exception, catching the type Exception will catch all the run time exceptions (like NullpointerException, ArrayIndexOut-OfBounds-Exception) as well.

No comments: