try...catch...finally中的return

1. 如果 finally 中没有 return,try和catch中第一个执行的 return作为返回值。(当返回值是可变对象时 finally 中的代码可以修改返回对象的值,比如 a.b=1,但已经不能修改返回对象的地址指向,比如 a = new A1())

 

2. 如果 finally 中有 return,try和catch中的 return 只起到阻止后续代码执行的作用,返回值以 finally 中的 return 为准。

 

3. try 和 catch 中的 return 会阻止后续代码的执行,但不会阻止 finally 中代码的执行。


============================


public class A1 {
    static A1 a = new A1();
    static int x1 = 10;
    private int b = 1;

    public static void main(String[] args) throws Exception {

        System.out.println("testA().b===" + testA().b);
        System.out.println("testB()===" + testB());
    }

    public static A1 testA() throws InterruptedException {
        try {
            int y1 = 1 / 0;
            return a;
        } catch (RuntimeException e) {
            a.b = 2;
            return a;
        } finally {
            a.b = a.b + 2;
        }
    }

    public static int testB() throws Exception {
        try {
            x1 = x1 + 5;
            x1 = x1 / 0;
            return x1;
        } catch (RuntimeException e) {
            x1 = x1 + 5;
            return x1;
        } finally {
            x1 = x1 + 5;
        }
    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值