9.1 Exception-Handling Mechanism | 435
outFile = new PrintWriter(new FileWriter(filename));
}
catch(IOException ioErr)
{
errorLabel.setText("Unable to open file "+ filename);
fileField.setText("");
}
Execution oftry-catch-finally When afinallyclause appears in atrystatement, the block follow-
ingfinallyis always executed, no matter what happens in thetryandcatchblocks. Thus, even
when acatchcauses a new exception, thefinallyblock executes. Thefinallyblock gives us
an opportunity to clean up after a failedcatch. In writing the algorithm for thefinallyblock,
however, it is important to realize that this block always executes, even if thetrysucceeds.
In this book we use only try-catchstatements, and we keep our exception handlers sim-
ple so that they won’t produce additional exceptions. The finallyclause is really needed
only when a catchcontains statements that might generate a new exception, and we need
to undo some of its processing before throwing the exception.
Generating an Exception with throw
Standard library classes are not the only classes that can generate exceptions. Here we in-
troduce the throwstatement, which we use when raising or generating an exception.
All exceptions are thrown by a throwstatement. Its syntax is quite simple:
The Object-Expression must be either a variable or a value of a reference type that can
be assigned to the class Throwable. That is, it must denote the address of an object of the
class Throwableor a subclass of Throwablesuch as Exception(which we discuss in the next sec-
tion). The class Throwableand all of its subclasses must have a String-returning getMessage
method. When an exception is thrown, the JVM looks for a catchclause that can handle that
specific class of exception.
The throwstatement may be written within a trystatement that is intended to catch it.
In that case, control is transferred to the catchclause with the corresponding class.
More often, the throwoccurs inside a method that is called from within a trystatement,
as shown in Figure 9.1. The JVM first looks for a catchwithin the method. When it fails to find
one, it causes the method to return. The JVM then looks around the point where the method
was called and finds an appropriate catchclause. The catchexecutes, and control transfers
to the statement following the try-catch.
If the JVM can’t find a matching catchwhen it forces the method to return, it causes the
method containing the call to return as well. The JVM looks around that call point for a try-
catch; if it can’t find one, it forces another return. The series of returns can lead all the way
throw Object-Expression;
Throw-Statement