Java Reference
In-Depth Information
catch
(Exception eRef)
{
System.out.println(eRef.toString());
}
}
}
Sample Run: If the input file does not exist, the following message is printed:
java.io.FileNotFoundException: test.txt (The system cannot find the
file specified)
The
try
block contains statements that open both the input and output files. It also contains
input and output statements. The first
catch
block catches a
FileNotFoundException
,
the second
catch
block catches all types of exceptions. As shown in the sample run, if
the input file does not exist, the statement in Step 2 in the
try
block throws a
FileNotFoundException
, which is caught and handled by the first
catch
block.
When an exception occurs in a
try
block, control immediately passes to the first
matching
catch
block. Typically, a
catch
block does one of the following:
Completely handles the exception.
Partially processes the exception. In this case, the
catch
block either
rethrows the same exception or throws another exception for the calling
environment to handle the exception.
Rethrows the same exception for the calling environment to handle the
exception.
The
catch
blocks in Examples 11-3 to 11-6 handled the exception. The mechanism of
rethrowing or throwing an exception is quite useful in cases when a
catch
block catches
the exception, but the
catch
block is unable to handle the exception, or if the
catch
block decides that the exception should be handled by the calling environment. This
allows the programmer to provide the exception handling code in one place.
Rethrowing an exception or throwing an exception is accomplished by the
throw
statement. A
throw
statement can throw either a checked or an unchecked exception.
Exceptions are objects of a specific
class
type. Therefore, if you have a reference to an
exception object, you can use the reference to throw the exception. In this case, the
general syntax to rethrow an exception caught by a
catch
block is:
1
1
throw
exceptionReference;
Search WWH ::
Custom Search