The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Essential Java Classes
Lesson: Handling Errors with Exceptions

The Throwable Class and Its Subclasses

As you learned on the previous page, you can throw only objects that derive from the Throwable class. This includes direct descendants (that is, objects that derive directly from the Throwable class) as well as indirect descendants (objects that derive from children or grandchildren of the Throwable class).

This diagram illustrates the class hierarchy of the Throwable class and its most significant subclasses.

As you can see from the diagram, Throwable has two direct descendants: Error and Exception.

Errors

When a dynamic linking failure or some other "hard" failure in the virtual machine occurs, the virtual machine throws an Error. Typical Java programs should not catch Errors. In addition, it's unlikely that typical Java programs will ever throw Errors either.

Exceptions

Most programs throw and catch objects that derive from the Exception class. Exceptions indicate that a problem occurred but that the problem is not a serious systemic problem. Most programs you write will throw and catch Exceptions.

The Exception class has many descendants defined in the Java packages. These descendants indicate various types of exceptions that can occur. For example, IllegalAccessException signals that a particular method could not be found, and NegativeArraySizeException indicates that a program attempted to create an array with a negative size.

One Exception subclass has special meaning in the Java language: RuntimeException.

Runtime Exceptions

The RuntimeException class represents exceptions that occur within the Java virtual machine (during runtime). An example of a runtime exception is NullPointerException, which occurs when a method tries to access a member of an object through a null reference. A NullPointerException can occur anywhere a program tries to dereference a reference to an object. The cost of checking for the exception often outweighs the benefit of catching it.

Because runtime exceptions are so ubiquitous and attempting to catch or specify all of them all the time would be a fruitless exercise (and a fruitful source of unreadable and unmaintainable code), the compiler allows runtime exceptions to go uncaught and unspecified.

The Java packages define several RuntimeException classes. You can catch these exceptions just like other exceptions. However, a method is not required to specify that it throws RuntimeExceptions. In addition, you can create your own RuntimeException subclasses. Runtime Exceptions--The Controversy contains a thorough discussion of when and how to use runtime exceptions.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2001 Sun Microsystems, Inc. All rights reserved.