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
try statement with a finally clause (§ 14.20.2 ) may be used.
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-
pressions in §15 (especially § 15.6 ) .
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.
Click here to view code image
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());
}
}
Search WWH ::




Custom Search