Java面试题3:try...catch...finally

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值