Wednesday, April 29, 2009

checked and unchecked exception



Checked Exceptions. These are the exception that must be caught if you call a method that throws Checked exception. A method that may throw such exception, must explicitly declare it in method signature.

Unchecked exceptions: They can be thrown anytime, they not forced to be caught by compiler. Methods do not have to declare that they can throw an unchecked exception. Error and RuntimeException and their subclasses are treated as unchecked exceptions by java compiler.


Exceptions represent errors from which a program can potentially recover.
Exceptions and all its subclasses except RuntimeException are "Checked" exception
if you call a method that throws an exception you must have a catch block or declare your method to throw the exception.


Runtime exceptions should represent errors due to programming error, and a program is not expected recover from such exceptions. A program may catch the exception with Catch block but is not forced to catch it by compiler as Runtime excptions are "uncheck exceptions". Example ArrayIndexOutOfBound, NullPointerException, ClassCastException, NumberFormatException

Error class is also "unchecked exceptions". They represent errors from which program can not recover. Example is OutOfMemoryError.

One should try to reuse existing exception classes. There should be a real good exception to write a new exception class.

Following are commonly used exception. IllegalArgumentException, IllegalStateException, NullPointerException, IndexOutOfBoundsException, ConcurrentModificationException, UnsupportedOperationException.

Exception chaining: wrap an exception in a new one and throw new exception.

Try handling them at lower level.

Document exceptions thrown by a method.

Include detailed error message.

Validate and throw exceptions early on in a method.

Don't ignore exceptions


Reference: Effective Java, 2nd edition.