Card 06/ 10
finally and return: Why a finally Block Must Not Return
A method that returns 1 in its try block and hands its caller 2.
A finally block runs on every way out of a try, including a return: the return value is worked out, the finally runs, and only then does the method return. A return written inside the finally replaces that value, and discards any exception on its way out.
The ordinary case first, a try that returns and a finally that prints:
static int value() {
try {
return 1;
} finally {
System.out.println("finally ran");
}
}finally ran
1A finally block runs on every way out of the try: falling off the end, returning, breaking, or throwing. The return on line 3 works out its value, then finally runs, then the method returns.
That much is useful and is what finally is for. The expensive version is a return inside the finally itself.
static int value() {
try {
return 1;
} finally {
return 2;
}
}Never return or throw from a finally block. Use it for cleanup and nothing else, and let whatever the try decided be what leaves the method.
← → move through sections and cards