Java Reference
In-Depth Information
Object
derived from
Throwable
derived from
derived from
Exception
Error
derived from
derived from
derived from
derived from
Exceptions you should not catch
Exceptions you can catch
Error Exceptions
The exceptions that are defined by the class Error , and its subclasses, are characterized by the fact that
they all represent conditions that you aren't expected to do anything about and, therefore, you aren't
expected to catch them. There are three direct subclasses of Error - ThreadDeath , LinkageError ,
and VirtualMachineError . The first of these sounds the most serious, but in fact it isn't. A
ThreadDeath exception is thrown whenever an executing thread is deliberately stopped, and in order
for the thread to be destroyed properly you should not catch this exception. There are circumstances
where you might want to - for clean-up operations for instance - in which case you must be sure to
rethrow the exception to allow the thread to die. When a ThreadDeath exception is thrown and not
caught, it's the thread that ends, not the program. We will deal with threads in detail in Chapter 11.
The LinkageError exception class has subclasses that record serious errors with the classes in your
program. Incompatibilities between classes or attempting to create an object of a non-existent class type
are the sorts of things that cause these exceptions to be thrown. The VirtualMachineError class has
four subclasses that specify exceptions that will be thrown when a catastrophic failure of the Java Virtual
Machine occurs. You aren't prohibited from trying to deal with these exceptions but, in general, there's
little point in attempting to catch them. The exceptions that correspond to objects of classes derived
from LinkageError and VirtualMachineError are all the result of catastrophic events or
conditions. There is little or nothing you can do to recover from them during the execution of the
program. In these sorts of situations, all you can usually do is read the error message generated by the
exception, and then, particularly in the case of a LinkageError exception, try to figure out what
might be wrong with your code to cause the exception to be thrown.
RuntimeException Exceptions
For almost all the exceptions that are represented by subclasses of the Exception class, you must
include code in your programs to deal with them if your code may cause them to be thrown. If a
method in your program has the potential to generate an exception of some such class, you must either
handle the exception within the method, or register that your method may throw such an exception. If
you don't, your program will not compile. We'll see in a moment how to handle exceptions and how to
specify that a method can throw an exception.
Search WWH ::




Custom Search