【发布时间】:2014-02-28 01:29:01
【问题描述】:
请检查以下代码并解释输出行为:
class ExceptionTest2 {
int x = 5;
public int TestMethod2() {
try {
x = x + 2;
System.out.println("x value in try: " + x);
return x;
} catch (Exception e) {
} finally {
x = x + 3;
System.out.println("x value in finally: " + x);
}
return x;
}
}
public class ExceptionProg2 {
public static void main(String[] args) {
ExceptionTest2 test2 = new ExceptionTest2();
int res = test2.TestMethod2();
System.out.println("Res : " + res); // it should return 10 but returning 7.
}
}
这里返回 7 而不是 10。
这是实际的o/p:
x value in try: 7
x value in finally: 10
Res : 7
为什么会这样,当 x 值在 finally 块中更改并且 'x' 不是局部变量时。
请澄清我的疑问。
【问题讨论】:
-
finnally代码块将始终被执行