2

In following code I want to understand the the behaviour of return statement.Finally block will always execute so this function will always return 30 ,but what is significance of return statement in try block.Does this return in try block return value to its caller, which will store this value in some stack and replaced when it see a return statement in finally block? or return in try block will call finally block?

public static int test() {
    try {
           return 10;// to whom this 10 is returned to?
    } catch (Exception e) {
       return 20;
    }finally{
           System.out.println("Finally");
       return 30;
    }
}

Thanks in advance.

Scorpion
  • 577
  • 4
  • 21
Ravi Godara
  • 497
  • 6
  • 20
  • possible duplicate of [Why is printed 1?](http://stackoverflow.com/questions/19651860/why-is-printed-1) – Rahul Feb 27 '14 at 12:19
  • Just as a warning: `finally` is meant for cleaning up resources and not for control flow. See http://stackoverflow.com/questions/48088/returning-from-a-finally-block-in-java and the topics linked from there for more details. – CompuChip Feb 27 '14 at 12:19

3 Answers3

1

Both 10 and 30 will return. But 30 is on top of the stack(top most element). so caller get the return value as 30.

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
1

finally block should be used for resource clearing only, e.g.

  public static int test() {
    MyResource resource = null;

    try {
      // resource allocation
      MyResource resource = MyResource.allocate();

      ... // do something with the resource

      return 10; // <- Normal flow
    } 
    catch(MyResourceException e) {
      ... // something was wrong with resource

      return 20; // <- Abnormal, but expected flow
    }
    finally {
      // In any case - has an exception (including errors) been thrown or not 
      // we have to release allocated resource 

      // The resource has been allocated 
      if (resource != null)
        resource.release();

      // no return here: finally is for resource clearing only
    }
  }

in case you put return 30 into finally both values (say, 10 and 30) will be put to stack; but since 30 will be on the top of the stack you'll see 30.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

Since the finally block will always be executed in your case for cleaning the reources the ouptut will be 30 since it will be on top of the stack. However if you want to come out of your try block directly then you may use System.exit()

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331