Multiple return statements without compiler error Multiple return statements without compiler error java java

Multiple return statements without compiler error


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.


This is described in the Java Language Specification:

§14.17

Abrupt completion of a finally clause can disrupt the transfer of control initiated by a return statement.

§14.20.2

If execution of the try block completes normally, then the finally block is executed, and then there is a choice:

  • If the finally block completes normally, then the try statement completes normally.
  • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S.

If execution of the try block completes abruptly for any other reason R, then the finally block is executed, and then there is a choice:

  • If the finally block completes normally, then the try statement completes abruptly for reason R.
  • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).


There are no compile time error since only 1 and exactly 1 of return statement will actually return the control back to calling code.

As explained @Hoopje, return within try or catch will execute first, their respective return statement will also execute. But just before returning the control back to calling code, it will execute the finally block. Now, this block also returns something, so this return overrides the previous one.