Considering this code, can I be absolutely sure that the finally block always executes, no matter what something() is?
try
Here's the official words from the Java Language Specification.
14.20.2. Execution of try-finally and try-catch-finally
A
trystatement with afinallyblock is executed by first executing thetryblock. Then there is a choice:
- If execution of the
tryblock completes normally, [...]- If execution of the
tryblock completes abruptly because of athrowof a value V, [...]- If execution of the
tryblock completes abruptly for any other reason R, then thefinallyblock is executed. Then there is a choice:
- If the finally block completes normally, then the
trystatement completes abruptly for reason R.- If the
finallyblock completes abruptly for reason S, then thetrystatement completes abruptly for reason S (and reason R is discarded).
The specification for return actually makes this explicit:
JLS 14.17 The return Statement
ReturnStatement: return Expression(opt) ;A
returnstatement with noExpressionattempts to transfer control to the invoker of the method or constructor that contains it.A
returnstatement with anExpressionattempts to transfer control to the invoker of the method that contains it; the value of theExpressionbecomes the value of the method invocation.The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any
trystatements within the method or constructor whosetryblocks contain thereturnstatement, then anyfinallyclauses of thosetrystatements will be executed, in order, innermost to outermost, before control is transferred to the invoker of the method or constructor. Abrupt completion of afinallyclause can disrupt the transfer of control initiated by areturnstatement.