Reason for Unaltered Return Value
In a try-finally statement, the try block's execution concludes with the execution of the return statement. At this point, the value of the variable s that is returned by the method is the value of s at the time the return statement is executed.
Even though the finally clause modifies the value of s later, it does not change the method's return value after the return statement has already executed.
Immutable vs Mutable Objects
It's important to note that this behavior applies when directly modifying the value of s itself in the finally block. However, if s referenced a mutable object (which String is not), modifying the object's contents within the finally block would be reflected in the returned value.
Legal Specification
The Java Language Specification (JLS) provides detailed guidelines for these operations in Section 14.20.2. In this section, it states that a return statement within a try block constitutes an abrupt termination. Consequently, Section 14.17 explains that a return statement abruptly ends block execution.
Exception Handling and Return Statements
If both the try block and finally block terminate abruptly due to return statements, the rules from §14.20.2 apply:
The consequence of these rules is that the return statement within the finally block determines the return value of the entire try-finally statement, overriding the return value from the try block. A similar phenomenon occurs in try-catch-finally statements where an exception is thrown in the try block and handled by a catch block, and both the catch and finally blocks contain return statements.
The above is the detailed content of Why Does a Return Statement in a Finally Block Override the Try Block's Return Value?. For more information, please follow other related articles on the PHP Chinese website!