Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^432) | Exceptions and Additional Control Structures


9.1 Exception-Handling Mechanism


In Chapter 8, we defined an exceptionas an unusual situation that is detected while an ap-
plication is running. An exception halts the normal execution of a method. There are three
parts to an exception-handling mechanism: defining the exception, raising or generating the
exception, and handling the exception. We look first at handling exceptions and then at
defining and raising them.

The try-catch-finally Statement


Ever since Chapter 2, when we introduced the BufferedReaderclass, we have found it neces-
sary to forward an IOExceptionto the JVM. We noted that the alternative to forwarding is to
catch an exception.
When an error occurs in a method call, it isn’t always possible for the method itself to
take care of it. For example, suppose we ask the user for a file name in a dialog, get the name
from a field, and then attempt to open the file (prepare it for reading by calling the
FileReaderconstructor). The constructor discovers that the file doesn’t exist and,
therefore, cannot open it. Perhaps the file has been deleted, or maybe the user
just mistyped the name. The constructor has no way of knowing that the proper
response to the error is to ask the user to reenter the name. Because the con-
structor can’t deal with this error appropriately, it doesn’t even try. It passes the
problem on to the method that called it, such as main.
When a call returns with an exception, normal execution ends and the JVM
looks to see whether code is available to take care of the problem. That code is called
an exception handlerand is part of a try-catch-finallystatement.
The syntax template for a try-catch-finallystatement follows:

As the diagram shows, the statement has three main parts. The first part is the keyword
tryand a block (a { }pair enclosing any number of statements). The second part is an op-
tional series of catchclauses, each consisting of the keyword catch, a single parameter dec-
laration enclosed in parentheses, and a block. The last part is also optional and consists of
the keyword finallyand a block.

try
Block

finally
Block

catch (Exception-Type Object-Name)
Block

...


Exception handler A section
of code that is executed when a
particular exception occurs. In
Java, an exception handler ap-
pears within a catchclause of a
try-catch-finallycontrol
structure.
Free download pdf