【发布时间】:2015-06-02 08:45:36
【问题描述】:
我对 finally 关键字的实际工作方式感到困惑......
在 try 块运行完成之前,它会返回到 方法被调用。但是,在它返回调用方法之前, finally 块中的代码仍然被执行。所以,请记住 finally 块中的代码即使有 try 块中某处的 return 语句。
当我运行代码时,我得到的是 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;
}
}
【问题讨论】:
-
finally block 在 return 语句之后执行,这就是为什么你得到 5 而不是 10