Java Reference
In-Depth Information
The constructors of the
class
es
FileReader
and
PrintWriter
that we used throw a
FileNotFoundException
. Therefore, these constructors throw a checked exception.
When the compiler encounters the statements to open an input or output file, it checks
whether the program handles
FileNotFoundExceptions
, or reports them by throwing
them. Enabling the compiler to check for these types of exceptions reduces the number
of exceptions not properly handled by the program. Because our programs so far were
not required to handle
FileNotFoundExceptions
or other types of predefined excep-
tions, the programs handled the checked exceptions by throwing them. (Another
common checked exception that can occur during program execution is known as
IOExceptions
. For example, the method
read
used in the Text Processing program-
ming example, in Chapter 9, may throw an
IOException
.)
When a program is being compiled, the compiler may not be able to determine whether
exceptions—such as division by zero, index out of bounds, or the next input is invalid—will
occur. Therefore, the compiler does not check these types of exceptions, called unchecked
exceptions. To significantly improve the correctness of programs, programmers must
check for these types of exceptions.
Because the compiler does not check for unchecked exceptions, the program does not
need to declare them using a
throws
clause or provide the code within the program
to deal with them. The exceptions belonging to a subclass of the
class
RuntimeException
are unchecked exceptions. Because
InputMismatchException
is a
subclass of the
class
RuntimeException
, the exceptions thrown by the methods
nextInt
and
nextDouble
are unchecked. Therefore, in all the programs that used the
methods
nextInt
and
nextDouble
, we did not use the
throws
clause to throw these
exceptions. If a program does not provide the code to handle an unchecked exception,
the exception is handled by Java's default exception handler.
In the method heading, the
throws
clause lists the types of exceptions thrown by the
method. The syntax of the
throws
clause is:
throws
ExceptionType1, ExceptionType2, ...
where
ExceptionType1
,
ExceptionType2
, and so on, are the names of the exception
classes.
For example, consider the following method:
public static void
exceptionMethod()
throws
InputMismatchException, FileNotFoundException
{
//statements
}
The method
exceptionMethod
throws exceptions of type
InputMismatchException
and
FileNotFoundException
.
Search WWH ::
Custom Search