Java Reference
In-Depth Information
TRy
blocks can be further complicated if both
pre
and the other actions
can throw the same exceptionsquite common with I/O operationsand we
wish to propagate the exception after using it in some way; an excep-
tion thrown by the other actions would get caught twice and we would
have to code our
catch
blocks to watch for and deal with that situation.
A
finally
clause can also be used to clean up for
break
,
continue
, and
return
, which is one reason you will sometimes see a
try
clause with no
catch
clauses. When any control transfer statement is executed, all rel-
evant
finally
clauses are executed. There is no way to leave a
try
block
without executing its
finally
clause.
The preceding example relies on
finally
in this way to clean up even
with a normal
return
. One of the most common reasons
goto
is used in
other languages is to ensure that certain things are cleaned up when a
block of code is complete, whether or not it was successful. In our ex-
ample, the
finally
clause ensures that the file is closed when either the
return
statement is executed or the stream throws an exception.
A
finally
clause is always entered with a reason. That reason may be
that the
try
code finished normally, that it executed a control flow state-
ment such as
return
, or that an exception was thrown in code executed
in the
TRy
block. The reason is remembered when the
finally
clause
exits by falling out the bottom. However, if the
finally
block creates
its own reason to leave by executing a control flow statement (such as
break
or
return
) or by throwing an exception, that reason supersedes the
original one, and the original reason is forgotten. For example, consider
the following code:
try {
// ... do something ...
return 1;
} finally {
return 2;
}