Multiple return statements without compiler error
Solution 1:
It does not give a compilation error because it is allowed by the Java Language Specification. However, it gives a warning message because including a return
statement in the finally
block is usually a bad idea.
What happens in your example is the following. The return
statement in the try
block is executed. However, the finally
block must always be executed so it is executed after the catch
block finishes. The return
statement occurring there overwrites the result of the previous return
statement, and so the method returns the second result.
Similarly a finally
block usually should not throw an exception. That's why the warning says that the finally
block should complete normally, that is, without return
or throwing an exception.
Solution 2:
This is described in the Java Language Specification:
§14.17
Abrupt completion of a
finally
clause can disrupt the transfer of control initiated by areturn
statement.
§14.20.2
If execution of the
try
block completes normally, then thefinally
block is executed, and then there is a choice:
- If the
finally
block completes normally, then thetry
statement completes normally.- If the
finally
block completes abruptly for reason S, then thetry
statement completes abruptly for reason S.If execution of the
try
block completes abruptly for any other reason R, then thefinally
block is executed, and then there is a choice:
- If the
finally
block completes normally, then thetry
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).