Java Reference
In-Depth Information
In situations where it is desirable to ensure that one block of code is always
executed after another, even if that other block of code completes abruptly, a
If a
try
or
catch
block in a
try
-
finally
or
try
-
catch
-
finally
statement completes ab-
ruptly, then the
finally
clause is executed during propagation of the exception,
even if no matching
catch
clause is ultimately found.
If a
finally
clause is executed because of abrupt completion of a
try
block and
the
finally
clause itself completes abruptly, then the reason for the abrupt com-
pletion of the
try
block is discarded and the new reason for abrupt completion
is propagated from there.
The exact rules for abrupt completion and for the catching of exceptions are
specified in detail with the specification of each statement in §14 and for ex-
Example 11.3-1. Throwing and Catching Exceptions
The following program declares an exception class
TestException
. The
main
method of
class
Test
invokes the
thrower
method four times, causing exceptions to be thrown three
of the four times. The
try
statement in method
main
catches each exception that the
thrower throws. Whether the invocation of
thrower
completes normally or abruptly, a
message is printed describing what happened.
class TestException extends Exception {
TestException() { super(); }
TestException(String s) { super(s); }
}
class Test {
public static void main(String[] args) {
for (String arg : args) {
try {
thrower(arg);
System.out.println("Test \"" + arg +
"\" didn't throw an exception");
} catch (Exception e) {
System.out.println("Test \"" + arg +
"\" threw a " + e.getClass() +
"\n with message: " +
e.getMessage());
}
}