Java Reference
In-Depth Information
Code 12.9
An exception handler
String filename = null ;
try {
filename = request-a-file-from-the-user;
addressbook.saveToFile(filename);
successful = true ;
}
catch (IOException e) {
System.out.println( "Unable to save to " + filename);
successful = false ;
}
The idea is that a try block represents a sequence of actions we wish to treat as a logical whole
but recognize that they might fail at some point. 5 The catch block will then attempt to deal with
the situation or report the problem if an exception arises from any statement within the associ-
ated try block. Note that, because both the try and catch blocks make use of the filename vari-
able, it has to be declared outside the try statement in this example, for reasons of scope.
In order to understand how an exception handler works, it is essential to appreciate that an excep-
tion prevents the normal flow of control from being continued in the caller . An exception inter-
rupts the execution of the caller's statements, and hence any statements immediately following the
problem statement will not be executed. The question then arises, “Where is execution resumed in
the caller?” A try statement provides the answer: if an exception arises from a statement called in
the try block, then execution is resumed in the corresponding catch block. So, if we consider the
example in Code 12.9, the effect of an IOException being thrown from the call to saveToFile
will be that control will transfer from the try block to the catch block, as shown in Code 12.10.
Statements in a try block are known as protected statements . If no exception arises during execu-
tion of protected statements, then the catch block will be skipped over when the end of the try
block is reached. Execution will continue with whatever follows the complete try/catch statement.
1 Exception thrown from here
2 Control transfers to here
Code 12.10
Transfer of control
in a try statement
try {
filename = request-a-file-from-the-user;
addressbook.saveToFile(filename);
successful = true ;
}
catch (IOException e) {
System.out.println( "Unable to save to " + filename);
successful = false ;
}
5
See Exercise 12.30 for an example of what can happen if a statement that might result in an exception is
treated in isolation from the statements around it.
 
Search WWH ::




Custom Search