What does this print?
static int f() {
try {
return 1;
} finally {
System.out.println("finally");
}
}
System.out.println(f());Options
- 1
- finally, then 1 (Correct option)
- 1, then finally
- finally only
Answer
finally, then 1
Why
A finally block runs always, even if the try block executes return. Java first evaluates the return value (1), then runs finally (printing "finally"), then returns 1 to the caller.
So the output is finally on one line and 1 on the next.
Do not put return inside finally: it would replace the original result and even hide exceptions.
Remember
finally always runs, even after return.