1
public class ReturnValueFromTryCatchFinally
{
    public static void main(String[] args)
    {
        System.out.println(methodReturningValue());
    }

    static String methodReturningValue()
    {
        String s = null;
        try
        {
            s = "return value from try block";
            return s;
        }
        catch (Exception e)
        {
            s = s + "return value from catch block";
            return s;
        }
        finally
        {
            s = s + "return value from finally block";
         //  return s;


        }
    }
}

If we run this program then we are getting output as "return value from try block". If we remove the comment from the finally block (return s;) then we are getting output "return value from try block return value from finally block".

Why isn't it giving the output "return value from try block" and "return value from try block return value from finally block"? Because first it will return from the try block then it goes to finally.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

2 Answers2

3

A function can't return twice. It's going to return one string or the other. It can't return both.

One of the two return statements will "win out" and decide what gets returned. As you can see from your testing, if a finally block has a return statement it overrides the return value from the try block.

If you're wondering why the finally block has no effect when the return statement is commented out, it's because in the try block returns the return value is (provisionally) set to "return value from try block". It is not set to "the value of s, whatever that may be". Updating s later in the finally block doesn't retroactively change the return value of the try block. It's already been locked in. The finally block can only change the return value if it has its own return statement.

For what it's worth, it is a very, very bad idea to have a finally block with a return statement. When an exception is thrown you want that exception to propagate to the caller. A return statement in a try block is skipped when there's an exception, but in a finally block it will be executed unconditionally and cause the exception to be suppressed. Don't put return inside of finally.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 1
    Most IDEs will warn you if you put `return`, `break`, `continue` or `throw` inside a `finally` block. It's also against numerous coding guidelines such as https://wiki.sei.cmu.edu/confluence/display/java/ERR04-J.+Do+not+complete+abruptly+from+a+finally+block . Also, in C#, it's a compilation error. – DodgyCodeException Jan 15 '18 at 16:45
0

Nope, a method returns only once. And the finally branch is executed just after your inner 'return s'.

Axel Podehl
  • 4,034
  • 29
  • 41