Java Reference
In-Depth Information
Unfortunately, when you try to compile a program that constructs a
Scanner
in
this manner, you'll run into a snag. Say you write a
main
method that begins by
opening a
Scanner
as follows:
// flawed method--does not compile
public static void main(String[] args) {
Scanner input = new Scanner(new File("hamlet.txt"));
...
}
This program does not compile. It produces a message like the following:
CountWords.java:8:
unreported exception java.io.FileNotFoundException;
must be caught or declared to be thrown
Scanner input = new Scanner(new File(hamlet.txt));
^
1 error
The issue involves exceptions, which were described in Chapter 3. Remember that
exceptions are errors that prevent a program from continuing normal execution. In
this case the compiler is worried that it might not be able to find a file called
hamlet.txt
. What is it supposed to do if that happens? It won't have a file to read
from, so it won't have any way to continue executing the rest of the code.
If the program is unable to locate the specified input file, it will generate an error
by throwing what is known as a
FileNotFoundException
. This particular exception
is known as a
checked exception.
Checked Exception
An exception that
must
be caught or specifically declared in the header of
the method that might generate it.
Because
FileNotFoundException
is a checked exception, you can't just ignore
it. Java provides a construct known as the
try/catch
statement for handling such
errors (described in Appendix D), but it allows you to avoid handling this error as
long as you clearly indicate the fact that you aren't handling it. All you have to do is
include a
clause
in the header for the
main
method to clearly state the fact
that your
main
method might generate this exception.
throws
throws
Clause
A declaration that a method will not attempt to handle a particular type of
exception.
Search WWH ::
Custom Search