如下程序会输出什么结果:
package 异常部分;
public class Test {
public static void main(String[] args) {
Demo d = new Demo();
System.out.println(d.method());
}
}
class Demo {
public int method() {
int x = 10;
try {
x = 20;
System.out.println(1 / 0);
return x;
} catch (Exception e) {
x = 30;
return x;
} finally {
x = 40;
}
}
}
结果是:30
finally中的代码块一定会执行,在除零异常发生时进入catch代码块,return回x的值为30,此时30就是返回给函数的最后的值。虽然执行了finally中的赋值但是40并不在return的返回路径中,因此最终返回的仍然是30