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
try
statement with afinally
block is executed by first executing thetry
block. Then there is a choice:
- If execution of the
try
block completes normally, [...]- If execution of the
try
block completes abruptly because of athrow
of a value V, [...]- If execution of the
try
block completes abruptly for any other reason R, then thefinally
block is executed. Then there is a choice:
- If the finally block completes normally, then the
try
statement completes abruptly for reason R.- If the
finally
block completes abruptly for reason S, then thetry
statement 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
return
statement with noExpression
attempts to transfer control to the invoker of the method or constructor that contains it.A
return
statement with anExpression
attempts to transfer control to the invoker of the method that contains it; the value of theExpression
becomes the value of the method invocation.The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any
try
statements within the method or constructor whosetry
blocks contain thereturn
statement, then anyfinally
clauses of thosetry
statements will be executed, in order, innermost to outermost, before control is transferred to the invoker of the method or constructor. Abrupt completion of afinally
clause can disrupt the transfer of control initiated by areturn
statement.