Java Reference
In-Depth Information
object. For instance, it is clear that the basic problem is a bad index when an
ArrayIndexOutBoundsException
is propagated. Exceptions are used to signal
exceptional occurrences
such as errors.
2.5.1
processing exceptions
The code in Figure 2.11 illustrates the use of exceptions. Code that might
result in the propagation of an exception is enclosed in a
try
block. The
try
block extends from lines 13 to 17. Immediately following the
try
block are
the exception handlers. This part of the code is jumped to only if an excep-
tion is raised; at the point the exception is raised, the
try
block in which it
came from is considered terminated. Each
catch
block (this code has only
one) is attempted in order until a matching handler is found. A
NumberFormatException
is generated by
parseInt
if
oneLine
is not convertible
to an
int
.
A
try
block
encloses code that
might generate an
exception.
The code in the
catch
block—in this case line 18—is executed if the
appropriate exception is matched. Then the
catch
block and the
try
/
catch
sequence is considered terminated.
1
A meaningful message is printed from
the exception object
e
. Alternatively, additional processing and more detailed
error messages could be given.
A
catch
block
processes an
exception.
2.5.2
the
finally
clause
Some objects that are created in a
try
block must be cleaned up. For instance,
files that are opened in the
try
block may need to be closed prior to leaving
the
try
block. One problem with this is that if an exception object is thrown
during execution of the
try
block, the cleanup might be omitted because the
exception will cause an immediate break from the
try
block. Although we can
place the cleanup immediately after the last
catch
clause, this works only if
the exception is caught by one of the
catch
clauses. And this may be difficult
to guarantee.
The
finally
clause that may follow the last
catch
block (or the
try
block,
if there are no
catch
blocks) is used in this situation. The
finally
clause con-
sists of the keyword
finally
followed by the
finally
block. There are three
basic scenarios.
The
finally
clause
is always executed
prior to completion
of a block, regard-
less of exceptions.
1. Note that both
try
and
catch
require a block and not simply a single statement. Thus braces
are not optional. To save space, we often place simple
catch
clauses on a single line with
their braces, indented two additional spaces, rather than use three lines. Later in the text we
will use this style for one-line methods.
Search WWH ::
Custom Search