Java Reference
In-Depth Information
Note the following about try / catch / finally blocks:
￿ If no exception is thrown in a try block, all catch blocks associated
with the try block are ignored and program execution resumes after the
last catch block.
￿ If an exception is thrown in a try block, the remaining statements in the
try block are ignored. The program searches the catch blocks in the
order in which they appear after the try block and looks for an appro-
priate exception handler.
￿ If the type of the thrown exception matches the parameter type in one of
the catch blocks, the code of that catch block executes and the
remaining catch blocks after this catch block are ignored.
￿ If there is a finally block after the last catch block, the finally block
executes regardless of whether an exception occurs.
As noted, when an exception occurs, an object of a particular exception class type is
created. The type of exception handled by a catch block is declared in the catch block
heading, which is the statement between the parentheses after the keyword catch .
Consider the following catch block:
catch (ArithmeticException aeRef)
{
//exception handler code
}
This catch block catches an exception of type ArithmeticException . The identifier
aeRef is a reference variable of type ArithmeticException . If an exception of type
ArithmeticException is thrown by the try block associated with this catch block,
and control reaches this catch block, then the reference parameter aeRef contains the
address of the exception object thrown by the try block. Because aeRef contains the
address of the exception object, you can access the exception object through the variable
aeRef . The object aeRef stores a detailed description of the thrown exception. You can
use the method toString (or the method getMessage ) to retrieve the message contain-
ing the description of the thrown exception. Example 11-3 illustrates how to use the
method toString to retrieve the description of the thrown exception.
1
1
ORDER OF catch BLOCKS
A catch block can catch either all exceptions of a specific type or all types of exceptions.
The heading of a catch block specifies the type of exception it handles. As discussed in
Chapter 10, a reference variable of a superclass type can point to an object of its subclass.
Therefore, if in the heading of a catch block you declare an exception using the class
Exception , then that catch block can catch all types of exceptions because the class
Exception is the superclass of all exception classes.
Suppose that an exception occurs in a try block and that exception is caught by a catch
block. Then, the remaining catch blocks associated with that try block are ignored.
Search WWH ::




Custom Search