Java Reference
In-Depth Information
finally
{
finalStatements;
}
The code in the
finally
block is executed under all circumstances, regardless of whether an
exception occurs in the
try
block or is caught. Consider three possible cases:
If no exception arises in the
try
block,
finalStatements
is executed, and the
next statement after the
try
statement is executed.
■
If a statement causes an exception in the
try
block that is caught in a
catch
block, the
rest of the statements in the
try
block are skipped, the
catch
block is executed, and
the
finally
clause is executed. The next statement after the
try
statement is executed.
■
If one of the statements causes an exception that is not caught in any
catch
block,
the other statements in the
try
block are skipped, the
finally
clause is executed,
and the exception is passed to the caller of this method.
■
The
finally
block executes even if there is a
return
statement prior to reaching the
finally
block.
Note
The
catch
block may be omitted when the
finally
clause is used.
A common use of the
finally
clause is in I/O programming. To ensure that a file
is closed under all circumstances, you may place a file closing statement in the
finally
block. Text I/O will be introduced later in this chapter.
omitting catch block
14.21
Suppose that
statement2
causes an exception in the following statement:
✓
✓
Check
try
{
statement1;
Point
statement2;
statement3;
}
catch
(Exception1 ex1) {
}
finally
{
statement4;
}
statement5;
Answer the following questions:
If no exception occurs, will
statement4
be executed, and will
statement5
be
executed?
■
If the exception is of type
Exception1
, will
statement4
be executed, and will
statement5
be executed?
■
If the exception is not of type
Exception1
, will
statement4
be executed, and
will
statement5
be executed?
■
A method should throw an exception if the error needs to be handled by its caller.
Key
Point
The
try
block contains the code that is executed in normal circumstances. The
catch
block
contains the code that is executed in exceptional circumstances. Exception handling separates
error-handling code from normal programming tasks, thus making programs easier to read