Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
As you learned on the previous page, you can throw only objects that derive from theThrowable
class. This includes direct descendants (that is, objects that derive directly from theThrowable
class) as well as indirect descendants (objects that derive from children or grandchildren of theThrowable
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
andException
.
When a dynamic linking failure or some other "hard" failure in the virtual machine occurs, the virtual machine throws anError
. Typical Java programs should not catchError
s. In addition, it's unlikely that typical Java programs will ever throwError
s either.
Most programs throw and catch objects that derive from theException
class.Exception
s indicate that a problem occurred but that the problem is not a serious systemic problem. Most programs you write will throw and catchException
s.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, andNegativeArraySizeException
indicates that a program attempted to create an array with a negative size.One
Exception
subclass has special meaning in the Java language:RuntimeException
.
TheRuntimeException
class represents exceptions that occur within the Java virtual machine (during runtime). An example of a runtime exception isNullPointerException
, which occurs when a method tries to access a member of an object through a null reference. ANullPointerException
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 throwsRuntimeExceptions
. In addition, you can create your ownRuntimeException
subclasses. Runtime Exceptions--The Controversy contains a thorough discussion of when and how to use runtime exceptions.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2001 Sun Microsystems, Inc. All rights reserved.