Java Reference
In-Depth Information
The
finally
Clause
A
try-catch
statement can have an optional
finally clause
. The
finally
clause defines a section of code that is executed no matter
how the
try
block is exited. Most often, a
finally
clause is used to
manage resources or to guarantee that particular parts of an algo-
rithm are executed.
If no exception is generated, the statements in the
finally
clause
are executed after the
try
block is complete. If an exception is generated in the
try
block, control first transfers to the appropriate
catch
clause. After executing the
exception-handling code, control transfers to the
finally
clause and its statements
are executed. A
finally
clause, if present, must be listed following the
catch
clauses.
Note that a
try
block does not need to have a
catch
clause at all. If there are
no
catch
clauses, a
finally
clause may used by itself if that is appropriate for
the situation.
KEY CONCEPT
The
finally
clause is executed
whether the
try
block is exited
normally or because of a thrown
exception.
SELF-REVIEW QUESTIONS
(see answers in Appendix N)
SR 11.4
What is a
catch
clause?
SR 11.5
What is a
finally
clause?
SR 11.6
What output is produced by the following code fragment under each
of the stated conditions?
try
{
review.question();
}
catch
(Exception1 exception)
{
System.out.println ("one caught");
}
catch
(Exception2 exception)
{
System.out.println ("two caught");
}
finally
{
System.out.println ("finally");
}
System.out.println ("the end");
a. No exception is thrown by the
review.question()
method.
Search WWH ::
Custom Search