0

finally always gets executed last, so the statement x = 3 should be executed last. But, when running this code, the value returned is 2.

Why?

class Test {
    public static void main (String[] args) {
        System.out.println(fina());
    }

    public static int fina()
    {
        int x = 0;
        try {
            x = 1;
            int a = 10/0;
        }
        catch (Exception e)
        {
            x = 2;
            return x;
        }
        finally
        {
            x = 3;
        }
        return x;
    }
}
Max Vollmer
  • 8,412
  • 9
  • 28
  • 43

2 Answers2

6

That's because the finally block is executed after the catch clause. Inside your catch you return x, and at that point its value is 2, which gets written to the stack as return value. Once finally overwrites the value of x with 3, the return value is already set to 2.

Max Vollmer
  • 8,412
  • 9
  • 28
  • 43
0

This is because you have a return statement in a catch block. Code is returning the value from that return statement even if the value is redefined in finally Block.

  • 2
    Well not quite, technically `finally` is still executed here. But it's not something which will change the outcome – Rogue Sep 13 '19 at 20:02
  • 1
    @Rogue To demonstrate your point, the OP can do `return 3;` instead of `return x` in the `finally`, and it will return `3` instead of `2` because the `finally` still executes. So this answer is wrong. – Nexevis Sep 13 '19 at 20:03
  • Maybe I was not clear in explaining. I meant the same thing what Max explained the return value was already set. – Makgigrahul Sep 13 '19 at 20:11
  • @Makgigrahul [edit] your answer to say what you mean if you don't think it is clear enough. – Andy Turner Sep 13 '19 at 20:13