5

Am confused about how finally keyword actually works...

Before the try block runs to completion it returns to wherever the method was invoked. But, before it returns to the invoking method, the code in the finally block is still executed. So, remember that the code in the finally block willstill be executed even if there is a return statement somewhere in the try block.

when I run the code, I get 5 instead of 10 as I expected

   public class Main {

    static int  count   = 0;
    Long        x;
    static Dog  d       = new Dog(5);

    public static void main(String[] args) throws Exception {
        System.out.println(xDog(d).getId());
    }

    public static Dog xDog(Dog d) {

        try {
            return d;
        } catch (Exception e) {
        } finally {
            d = new Dog(10);

        }
        return d;

    }
}

public class Dog {

    private int id;

    public Dog(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

}
Exorcismus
  • 2,243
  • 1
  • 35
  • 68

2 Answers2

9

The finally block is executed not before the return statement, but before actual return. This means that the expression in return statement is evaluated before the finally block is executed. In your case when you write return d the d expression is evaluated and stored into register, then finally is executed and the value from that register is returned. There's no way to alter the content of that register.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
  • 2
    If the `Dog` Class had a setter, and he would execute `d.setId(10);` in `finally`, he would change the value of the Dog – Loki Jun 02 '15 at 08:51
0

Your code does work correctly and the statement does run in the finally block. The only reason you don't get 10 is because you don't return the value you set the finally block. The code outside finally block does not get run since it already returns it in try block. To make your code work you simply change your xDog method to this.

public static Dog xDog(Dog d) 
{ 
    try 
    { 
        return d; 
    } 
    catch (Exception e) 
    { } 
    finally 
    { 
        d = new Dog(10); 
        return d;
    }
}

I hope this helped you.

Nanhydrin
  • 4,332
  • 2
  • 38
  • 51
EgorDm
  • 26
  • 1
  • 5