Programming and Problem Solving with Java

(やまだぃちぅ) #1
9.1 Exception-Handling Mechanism | 433

When a statement or series of statements in an application may result in an exception,
we enclose them in the block following try. For each type of exception that can be produced
by the statements, we write a catchclause. Here’s an example:


try
{
... // Statements that try to open a file
}
catch(IOException ioErr)
{
... // Statements that execute if the file can't be opened
}
finally
{
... // Statements that are always executed
}


The trystatement is meant to sound something like the coach telling the gymnast, “Go
ahead and try this move that you’re unsure of, and I’ll catch you if you fall.” We are telling
the computer to try executing some operations that might fail, and then providing code to
catch the potential exceptions. The finallyclause provides an opportunity to clean up, re-
gardless of what happens in the tryand catchblocks. We focus on the execution of a trystate-
ment without a finallyclause (a try-catchstatement) and briefly describe at the end of this
section what happens when we add the finallyclause.


Execution of try-catch If none of the statements in the tryblock throws an exception, then con-


trol transfers to the statement following the entire try-catchstatement. That is, we try some
statements, and if everything goes according to plan we continue on with the succeeding
statements.
When an exception occurs, control immediately transfers to the block associated with
the appropriate catch. It is important to recognize that control jumps directly from whatever
statement caused the exception to the catchblock. If statements appear in the tryblock fol-
lowing the one that caused the exception, they are skipped. If the catchblock executes with-
out causing any new exceptions, then control transfers to the next statement outside of the
try-catchstructure.
How does the computer know which catchis appropriate? It looks at the class of the pa-
rameter declared in each one and selects the first one with a class that matches the thrown
exception. Given how Java uses objects for just about everything, it should come as no sur-
prise to learn that an exception is an object and has a class. We’ve already seen three such
classes: IOException,NumberFormatException, and ClassNotFoundException. Another of these
classes is ArithmeticException, which is thrown when we attempt to execute an invalid arith-
metic operation (such as integer division by zero).

Free download pdf