Java Reference
In-Depth Information
Figure 12.1
The exception
class hierarchy
7KURZDEOH
VWDQGDUGOLEUDU\FODVVHV
XVHUGHILQHGFODVVHV
(UURU
([FHSWLRQ
MyCheckedException
5XQWLPH([FHSWLRQ
MyUncheckedException
speaking, exception classes are always subclasses of the Throwable class that is defined in
the java.lang package. We shall follow the convention of defining and using exception
classes that are subclasses of the Exception class, also defined in java.lang . 2 The java.
lang package defines a number of commonly seen exception classes that you might already
have run across inadvertently in developing programs, such as NullPointerException ,
IndexOutOfBoundsException , and ClassCastException .
Java divides exception classes into two categories: checked exceptions and unchecked excep-
tions. All subclasses of the Java standard class RuntimeException are unchecked exceptions;
all other subclasses of Exception are checked exceptions.
Slightly simplified, the difference is this: checked exceptions are intended for cases where the
client should expect that an operation could fail (for example, if it tries to write to a disk, it
should anticipate that the disk could be full). In such cases, the client will be forced to check
whether the operation was successful. Unchecked exceptions are intended for cases that should
never fail in normal operation—they usually indicate a program error. For instance, a program-
mer would never knowingly try to get an item from a position in a list that does not exist, so
when they do, it elicits an unchecked exception.
Unfortunately, knowing which category of exception to throw in any particular circumstance is
not an exact science, but we can offer the following general advice:
One rule of thumb is to use unchecked exceptions for situations that should lead to program
failure—typically because it is suspected that there is a logical error in the program that will
prevent it from continuing any further. It follows that checked exceptions should be used
2 Exception is one of two direct subclasses of Throwable ; the other is Error . Subclasses of Error
are usually reserved for runtime-system errors rather than errors over which the programmer has control.
 
Search WWH ::




Custom Search