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.
omit catch block
12.21
✓
✓
Suppose that
statement2
causes an exception in the following statement:
Check
Point
try
{
statement1;
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
and to modify. Be aware, however, that exception handling usually requires more time and
resources, because it requires instantiating a new exception object, rolling back the call stack,
and propagating the exception through the chain of methods invoked to search for the handler.
Search WWH ::
Custom Search