finally 四道经典异常处理代码题

题目一、

public class Test {
    public static void main(String[] args) {
        System.out.println(test());
    }
    public static int test() {
        try {
            return 1;
        } catch (Exception e) {
            return 2;
        } finally {
            System.out.print("3");
        }
    }
}
//输出:
31

try、catch、finally 的基础用法,在 return 前会先执行 finally 语句块,所以会先输出 finally 里的 3,再输出 return 的 1。由于这里try中没有异常发生,因此catch中的return不会执行

题目二、

public class Test {
    public static void main(String[] args) {
        System.out.println(test());
    }
    public static int test() {
        try {
            int i = 1/0;
            return 1;
        } catch (Exception e) {
            return 2;
        } finally {
            System.out.print("3");
        }
    }
}
//输出:
32

在 return 前会先执行 finally 语句块,所以会先输出 finally 里的 3,再输出 catch 中 return 的 2。由于这里try中有异常发生,因此try后续语句不会再执行

题目三、

public class Test {
    public static void main(String[] args) {
        System.out.println(test());
    }
    public static int test() {
        try {
            return 2;
        } finally {
            return 3;
        }
    }
}
//输出:
3

try中的return前先执行 finally,结果 finally 直接 return 了,自然也就走不到 try 里面的 return 了。

题目四、

public class Test {
    public static void main(String[] args) {
        System.out.println(test());
    }
    public static int test() {
        int i = 0;
        try {
            i = 2;
            return i;
        } finally {
            i = 3;
        }
    }
}
//输出:
2

在执行 finally 之前,JVM 会先将 i 的结果暂存起来,然后 finally 执行完毕后,会返回之前暂存的结果,而不是返回 i,所以即使 i 已经被修改为 3,最终返回的还是之前暂存起来的结果 2。

总结

  1. 无论try中是否有return,是否有异常,finally都一定会执行。
  2. 如果try中有异常发生,会执行catch中的句子,try中异常后续的位置的语句不会再被执行
  3. 当try与finally语句中均有return语句,会忽略try中return。
  4. try中有return, 会先将值暂存,无论finally语句中对该值做什么处理,最终返回的都是try语句中的暂存值。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值