After the great captains and engineers have accomplish'd their work,
After the noble inventorsafter the scientists, the chemist,
the geologist, ethnologist,
Finally shall come the Poet . . .
Walt Whitman, Passage to India (1870)
A try statement with a finally block is executed by first executing the try
block. Then there is a choice:
try block completes normally, then the finally block is executed, and then there is a choice:
finally block completes normally, then the try statement completes normally.
finally block completes abruptly for reason S, then the try statement completes abruptly for reason S.
try block completes abruptly because of a throw of a value V, then there is a choice:
catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed. Then there is a choice:
catch block completes normally, then the finally block is executed. Then there is a choice:
finally block completes normally, then the try statement completes normally.
finally block completes abruptly for any reason, then the try statement completes abruptly for the same reason.
catch block completes abruptly for reason R, then the finally block is executed. Then there is a choice:
catch clause of the try statement, then the finally block is executed. Then there is a choice:
try block completes abruptly for any other reason R, then the finally block is executed. Then there is a choice:
class BlewIt extends Exception {
BlewIt() { }
BlewIt(String s) { super(s); }
}
class Test {
static void blowUp() throws BlewIt {
throw new NullPointerException();
}
public static void main(String[] args) {
try {
blowUp();
} catch (BlewIt b) {
System.out.println("BlewIt");
} finally {
System.out.println("Uncaught Exception");
}
}
}
Uncaught Exception java.lang.NullPointerException at Test.blowUp(Test.java:7) at Test.main(Test.java:11)
The NullPointerException (which is a kind of RuntimeException) that is
thrown by method blowUp is not caught by the try statement in main, because a
NullPointerException is not assignable to a variable of type BlewIt. This
causes the finally clause to execute, after which the thread executing main,
which is the only thread of the test program, terminates because of an uncaught
exception (§20.21.31), which results in printing the exception name and a simple
backtrace.