5.6 Exception Types

Exceptions in Java are objects. All exceptions are derived from the java.lang. Throwable class. Figure 5.8 shows a partial hierarchy of classes derived from the Throwable class. The two main subclasses Exception and Error constitute the main categories of throwables, the term used to refer to both exceptions and errors. Figure 5.8 also shows that not all exception classes are found in the same package.

Figure 5.8. Partial Exception Inheritance Hierarchy

graphics/05fig08.jpg

The Throwable class provides a String variable that can be set by the subclasses to provide a detail message. The purpose of the detail message is to provide more information about the actual exception. All classes of throwables define a one-parameter constructor that takes a string as the detail message.

The class Throwable provides the following common methods to query an exeception:

String getMessage()

Returns the detail message.

void printStackTrace()

Prints the stack trace on the standard error stream. The stack trace comprises the method invocation sequence on the runtime stack when the exception was thrown. The stack trace can also be written to a PrintStream or a PrintWriter by supplying such a destination as an argument to one of the two overloaded printStackTrace() methods.

String toString()

Returns a short description of the exception, which typically comprises the class name of the exception together with the string returned by the getMessage() method.


Class Exception

The class Exception represents exceptions that a program would want to be made aware of during execution. Its subclass RuntimeException represents many common programming errors that manifest at runtime (see the next subsection). Other subclasses of the Exception class define other categories of exceptions, for example, I/O-related exceptions (IOException, FileNotFoundException, EOFException) and GUI-related exceptions (AWTException).

Class RuntimeException

Runtime exceptions, like out-of-bound array indices (ArrayIndexOutOfBounds Exception), uninitialized references (NullPointerException), illegal casting of references (ClassCastException), illegal parameters (IllegalArgumentException), division by zero (ArithmeticException), and number format problems (NumberFormatException) are all subclasses of the java.lang.RuntimeException class, which is a subclass of the Exception class. As these runtime exceptions are usually caused by program bugs that should not occur in the first place, it is more appropriate to treat them as faults in the program design, rather than merely catching them during program execution.

Class Error

The subclass AssertionError of the java.lang.Error class is used by the Java assertion facility (see Section 5.10, p. 208). Other subclasses of the java.lang.Error class define exceptions that indicate class linkage (LinkageError), thread (ThreadDeath), and virtual machine (VirtualMachineError) related problems. These are invariably never explicitly caught and are usually irrecoverable.

Checked and Unchecked Exceptions

Except for RuntimeException, Error, and their subclasses, all exceptions are called checked exceptions. The compiler ensures that if a method can throw a checked exception, directly or indirectly, then the method must explicitly deal with it. The method must either catch the exception and take the appropriate action, or pass the exception on to its caller (see Section 5.9, p. 201).

Exceptions defined by Error and RuntimeException classes and their subclasses are known as unchecked exceptions, meaning that a method is not obliged to deal with these kinds of exceptions (shown with grey color in Figure 5.8). They are either irrecoverable (exemplified by the Error class) and the program should not attempt to deal with them, or they are programming errors (examplified by the RuntimeException class) and should be dealt with as such and not as exceptions.

Defining New Exceptions

New exceptions are usually defined to provide fine-grained categorization of exceptional conditions, instead of using existing exception classes with descriptive detail messages to differentiate between the conditions. New exceptions usually extend the Exception class directly or one of its checked subclasses, thereby making the new exceptions checked.

As exceptions are defined by classes, they can declare fields and methods, thus providing more information as to their cause and remedy when they are thrown and caught. The super() call can be used to set a detail message in the throwable. Note that the exception class must be instantiated to create an exception object that can be thrown and subsequently caught and dealt with. The code below sketches a class definition for an exception that can include all pertinent information about the exception.

public class EvacuateException extends Exception {
    // Data
    Date date;
    Zone zone;
    TransportMode transport;

    // Constructor
    public EvacuateException(Date d, Zone z, TransportMode t) {
         // Call the constructor of the superclass
         super("Evacuation of zone " + z);
         // ...
    }
    // Methods
    // ...
}

Several examples illustrate exception handling in the subsequent sections.