What's the difference between a checked and an unchecked exception?
Author: Deron Eriksson
Description: This tutorial describes the differences between checked and unchecked exceptions in Java.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)
In JavaSW, the Exception class is a subclass of Throwable. The RuntimeException class is a subclass of Exception. If an exception is a subclass of Exception but not RuntimeException, it is a checked exception. A checked exception needs to either be caught in a method (in a try/catch block), or the method needs to specify that it can throw the exception on further (via a throws clause of a method declaration). If an exception is a subclass of RuntimeException, it is an unchecked exception. An unchecked exception can be caught, but it does not have to be. Thus, it is 'unchecked'. An example of a typical checked exception is IOException. An example of a typical unchecked exception is a NullPointerException. Here is an example of a checked exception class called CheckedException. It subclasses Exception. This exception class allows us to specify the exception message via a String argument to the constructor. CheckedException.javapackage test; public class CheckedException extends Exception { public CheckedException(String message) { super(message); } } Here we can see the Type Hierarchy of CheckedException. Notice that it is a subclass of Exception, and Exception is a subclass of Throwable. Here is a simple example of an unchecked exception class called UncheckedException. It subclasses RuntimeException. We can specify the exception message via the String argument to the constructor. UncheckedException.javapackage test; public class UncheckedException extends RuntimeException { public UncheckedException(String message) { super(message); } } Here is the Type Hierarchy for UncheckedException. Notice that it subclasses RuntimeException. (Continued on page 2) Related Tutorials: |