Java Reference
In-Depth Information
Checked exceptions are due to external circumstances that the programmer cannot
prevent. The compiler checks that your program handles these exceptions.
The compiler doesn't check whether you handle a
NullPointer-Exception
,
because you should test your references for
null
before using them rather than
install a handler for that exception. The compiler does insist that your program be
able to handle error conditions that you cannot prevent.
Actually, those categories aren't perfect. For example, the
Scanner.nextInt
method throws an unchecked
InputMismatchException
if a user enters an
input that is not an integer. A checked exception would have been more appropriate
because the programmer cannot prevent users from entering incorrect input. (The
designers of the
Scanner
class made this choice to make the class easy to use for
beginning programmers.)
As you can see from
Figure 1
, the majority of checked exceptions occur when you
deal with input and output. That is a fertile ground for external failures beyond your
controlȌa file might have been corrupted or removed, a network connection might
be overloaded, a server might have crashed, and so on. Therefore, you will need to
deal with checked exceptions principally when programming with files and streams.
You have seen how to use the
Scanner
class to read data from a file, by passing a
FileReader
object to the
Scanner
constructor:
String filename = . . .;
FileReader reader = new FileReader(filename);
Scanner in = new Scanner(reader);
506
507
However, the
FileReader
constructor can throw a
FileNotFoundException
.
The
FileNotFoundException
is a checked exception, so you need to tell the
compiler what you are going to do about it. You have two choices. You can handle
the exception, using the techniques that you will see in
Section 11.4
. Or you can
simply tell the compiler that you are aware of this exception and that you want your
method to be terminated when it occurs. The method that reads input rarely knows
what to do about an unexpected error, so that is usually the better option.
To declare that a method should be terminated when a checked exception occurs
within it, tag the method with a
throws
specifier.