Apurva Priyadarshi
Apurva Priyadarshi

Reputation: 33

Why return is not honoring the value of variable in finally block?

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;
    }
}

Upvotes: 0

Views: 98

Answers (2)

Makgigrahul
Makgigrahul

Reputation: 21

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.

Upvotes: 0

Max Vollmer
Max Vollmer

Reputation: 8598

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.

Upvotes: 6

Related Questions