我很困惑关于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)
finally块不是在return语句之前执行,而是在实际返回之前执行.这意味着在return执行finally块之前计算语句中的表达式.在你的情况,当你写return d的d表达式并存入寄存器,然后finally执行,并返回从该寄存器中的值.没有办法改变该寄存器的内容.
| 归档时间: |
|
| 查看次数: |
177 次 |
| 最近记录: |