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.