Search This Blog

Friday, July 07, 2006

Types of Exceptions

Java provides support for both checked and unchecked exceptions. The main differences between these exceptions is summarised below.

Checked Exception
extends Exception
caller must handle exception
e.g. FileNotFoundException

Unchecked Exception
extends RuntimeException
caller does not have to handle exception
e.g. NullPointerException

So, when should you use checked exceptions and when should you use unchecked exceptions?

A good guidline is to throw checked exceptions when the caller can reasonable handle a failure and can perform appropriate action. For example a client could easily perform some corrective action if a FileNotFound exception were to be thrown. If however the system throws a ClassCastException (which is an unchecked exception), there's not much that the caller could do about this. In this case, it may be better to throw a unchecked exception.

In J2EE containers, unchecked exceptions are caught by the container, and would, for example, cause an EJB transaction to be rolled back.

In Spring, unchecked exceptions are used extensively for data access code in the form of DataAccessExceptions. Typically if an error occurs in data access code, the client application cannot recover and a roll-back operation is performed. In this case unchecked exceptions (e.g. DataAccessException) are appropriate.

No comments: