World of tricky Core Java Q and A Covering Object Oriented Analysis and Design, JVM Internals,Java Language Fundamentals,Datatypes,Keywords,Operators and Assignments,Identifies,Declarations and Modifiers, Conversion,Casting and Promotion, Flow control,Assertions, Exception Handling and Garbage Collection,Objects and Classes), Basic Packages and their classes,JDBC,JFC Swing,Java Server Pages (JSP), Servlets,EJB,JMS,JNDI etc and Open source technologies like Struts,Hibernate,Spring etc
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.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment