终于没有按预期工作了

Exo*_*mus 5 java finally

我很困惑关于finally关键字实际上如何运作...

在try块运行完成之前,它将返回到调用方法的任何位置.但是,在它返回到调用方法之前,finally块中的代码仍然执行.所以,请记住,即使try块中某处有return语句,finally块中的代码也会被执行.

当我运行代码时,我得到5而不是我预期的10

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

}
Run Code Online (Sandbox Code Playgroud)

Tag*_*eev 9

finally块不是在return语句之前执行,而是在实际返回之前执行.这意味着在return执行finally块之前计算语句中的表达式.在你的情况,当你写return dd表达式并存入寄存器,然后finally执行,并返回从该寄存器中的值.没有办法改变该寄存器的内容.

  • 如果`Dog`类有一个setter,他会执行`d.setId(10);`````,他会更改Dog的值 (2认同)