Java's 'finally' Block Runs Before Exit, But Not Before Return Value Is Saved
A common Java misconception is that reassigning a variable inside a 'finally' block will change the value returned by a method, but the actual returned value is 1, not 99. This is because the JVM evaluates and stores the return expression in a hidden temporary variable before executing the 'finally' block. The stored value is what gets returned, so any reassignment of a primitive inside 'finally' has no effect on the result. However, mutating an object inside 'finally' does affect the outcome, since only the reference is captured, not a copy of the object. A 'return' statement placed inside a 'finally' block overrides everything, including pending exceptions, which is widely considered a bug-prone pattern.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.

Discussion (0)
Log in to join the discussion and vote.
Log in