|
|
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 theThrowableclass. This includes direct descendants (that is, objects that derive directly from theThrowableclass) as well as indirect descendants (objects that derive from children or grandchildren of theThrowableclass).This diagram illustrates the class hierarchy of the
Throwableclass and its most significant subclasses.As you can see from the diagram, Throwablehas two direct descendants:ErrorandException.
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 catchErrors. In addition, it's unlikely that typical Java programs will ever throwErrors either.
Most programs throw and catch objects that derive from theExceptionclass.Exceptions indicate that a problem occurred but that the problem is not a serious systemic problem. Most programs you write will throw and catchExceptions.The
Exceptionclass has many descendants defined in the Java packages. These descendants indicate various types of exceptions that can occur. For example,IllegalAccessExceptionsignals that a particular method could not be found, andNegativeArraySizeExceptionindicates that a program attempted to create an array with a negative size.One
Exceptionsubclass has special meaning in the Java language:RuntimeException.
TheRuntimeExceptionclass 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. ANullPointerExceptioncan 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
RuntimeExceptionclasses. 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 ownRuntimeExceptionsubclasses. 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-2004 Sun Microsystems, Inc. All rights reserved.