Considering this code, can I be absolutely sure that the finally
block always executes, no matter what something()
is?
try
The Java Language specification describes how try
-catch
-finally
and try
-catch
blocks work at 14.20.2
In no place it specifies that the finally
block is always executed.
But for all cases in which the try
-catch
-finally
and try
-finally
blocks complete it does specify that before completion finally
must be executed.
try {
CODE inside the try block
}
finally {
FIN code inside finally block
}
NEXT code executed after the try-finally block (may be in a different method).
The JLS does not guarantee that FIN is executed after CODE. The JLS guarantees that if CODE and NEXT are executed then FIN will always be executed after CODE and before NEXT.
Why doesn't the JLS guarantee that the finally
block is always executed after the try
block? Because it is impossible. It is unlikely but possible that the JVM will be aborted (kill, crash, power off) just after completing the try
block but before execution of the finally
block. There is nothing the JLS can do to avoid this.
Thus, any software which for their proper behaviour depends on finally
blocks always being executed after their try
blocks complete are bugged.
return
instructions in the try
block are irrelevant to this issue. If execution reaches code after the try
-catch
-finally
it is guaranteed that the finally
block will have been executed before, with or without return
instructions inside the try
block.