Java Reference
In-Depth Information
Now suppose that one of the methods before the last line throws an exception. Then
the call to
close
is never executed! Solve this problem by placing the call to
close
inside a
finally
clause:
PrintWriter out = new PrintWriter(filename);
try
{
writeData(out);
}
finally
{
out.close();
}
511
512
In a normal case, there will be no problem. When the
try
block is completed, the
finally
clause is executed, and the writer is closed. However, if an exception
occurs, the
finally
clause is also executed before the exception is passed to its
handler.
Once a
try
block is entered, the statements in a
finally
clause are guaranteed
to be executed, whether or not an exception is thrown.
Use the
finally
clause whenever you need to do some clean up, such as closing a
file, to ensure that the clean up happens no matter how the method exits.
It is also possible to have a
finally
clause following one or more
catch
clauses.
Then the code in the
finally
clause is executed whenever the
try
block is exited
in any of three ways:
1.
After completing the last statement of the
try
block
2.
After completing the last statement of a
catch
clause, if this
try
block
caught an exception
3.
When an exception was thrown in the
try
block and not caught
S
YNTAX
11.4
finally
Clause
try
{