3 下面代码有什么问题?
try {
return 0;
} catch (Exception e){
return 1;
} finally {
return 2;
}
return 3;
答:
最后的return 3; 会导致编译报错:Unreachable code。
分析:
(1)不管try块、catch块中是否有return语句,finally块都会执行。
(2)finally块中的return语句会覆盖前面的return语句(try块、catch块中的return语句),所以如果finally块中有return语句,Eclipse编译器会报警告“finally block does not complete normally”。
(3)如果finally块中包含了return语句,即使前面的catch块重新抛出了异常,则调用该方法的语句也不会获得catch块重新抛出的异常,而是会得到finally块的返回值,并且不会捕获异常。
实验1:
public class MyTest {
public static int func() {
try {
return 0;
} catch (Exception e){
return 1;
} finally {
return 2;
}
}
public static void main(String[] args) {
int res = func();
System.out.println("res=" + res);
}
}
运行结果:
res=2
实验2:
public class MyTest {
public static int func() {
try {
int a = 2 / 0;
return 0;
} catch (Exception e){
System.out.println("捕获异常:");
e.printStackTrace();
return 1;
} finally {
return 2;
}
}
public static void main(String[] args) {
int res = func();
System.out.println("res=" + res);
}
}
运行结果:
捕获异常:
java.lang.ArithmeticException: / by zero
at Test.func(Test.java:6)
at Test.main(Test.java:18)
res=2