Exceptions: When Things Go Wrong
10.3 Java’s Exception Hierarchy
Checked and Unchecked Exceptions
Java’s exception hierarchy is divided into two types of exceptions. A checked exception is one that can be analyzed by the Java compiler.
Checked exceptions are thrown by methods such as the BufferedReader.readLine() method, in which there is a substantial likelihood
that something might go wrong. When the compiler encounters one
of these method calls, it checks whether the program either handles or
declares the exception. Compile-time checking for these exceptions is
designed to reduce the number of exceptions that are not properly handled within a program. This improves the security of Java programs.
The throws Clause
The IOException, which we encountered in Chapter 4 , is a checked
exception. The Java compiler knows that readLine() is a method that
can throw an IOException. A method that contains an expression that
might throw a checked exception must either handle the exception or declare it. Otherwise, the compiler would generate a syntax error. The simplest way to avoid such a syntax error is to declare the exception, in our case
that means qualifying the method header with the expression throws
IOException.
In general, any method that contains an expression that might throw a
checked expression must declare the exception. However, because one
method can call another method, declaring exceptions can get a little
tricky. If a method calls another method that contains an expression that might throw an unchecked exception, then both methods must have a
throws clause. For example, consider the following program:
In this case, the doRead() method contains a readLine() expression, which might throw an IOException. Therefore, the doRead()
method must declare that it throws IOException. However, because
doRead() is called by main(), the main() method must also declare the
IOException.
The alternative approach would be to catch the IOException within
the body of the method. We will discuss this approach in the next section.
Unchecked Exceptions
An unchecked exception is any exception belonging to a subclass of
RuntimeException (Fig. 10.4). Unchecked exceptions are not checked
by the compiler. The possibility that some statement or expression will
lead to an ArithmeticException or NullPointerException is extremely difficult to detect at compile time. The designers of Java decided
that forcing programmers to declare such exceptions would not significantly improve the correctness of Java programs.
Therefore, unchecked exceptions do not have to be handled within
a program. And they do not have to be declared in a throws clause. As shown in the chapter’s early divide-by-zero exception example,
unchecked exceptions are handled by Java’s default exception handlers,
unless your program takes specific steps to handle them directly. In many cases leaving the handling of such exceptions up to Java may be the best
course of action, as we will see Section 10.5.