try{}catch{}finally{}的return执行逻辑

try{}catch{}finally{}代码块里面都有return:

public class DemoTest {
    public static void main(String[] args) {
        int num = getNum();
        System.out.println("执行结果:   " +num);
    }

    public static int getNum() {
        int i;
        try {
            i = 8;
            System.out.println("try块中的i的值:  "+i);
            int a = 90 / 0;
            return i;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            i = 5;
            return i;
        } finally {
            // finally中的代码一定会执行
            System.out.println("执行finally~~~");
            i = 6666;// 此处重新给i赋值
            System.out.println("finally 块中的值:  "+i);
            return i;// 无论如何总会在此处返回i的值
        }
    }
}

执行结果:
无论是否发生异常总是返回finally中的值.
在这里插入图片描述

return在try{}catch{}代码块里面,finally{}代码块中没有return:

public class DemoTest {
    public static void main(String[] args) {
        int num = getNum();
        System.out.println("执行结果:   " +num);
    }

    public static int getNum() {
        int i;
        try {
            i = 8;
            System.out.println("try块中的i的值:  "+i);
//            int a = 90 / 0;
            return i;// 没有异常会在此处返回i的值
        } catch (Exception e) {
            System.out.println(e.getMessage());
            i = 5;
            return i;// catch了异常之后会在此处返回i的值
        } finally {
            // finally中的代码一定会执行
            System.out.println("执行finally~~~");
            i = 6666;// 此处重新给i赋值
            System.out.println("finally 块中的值:  "+i);
        }
    }
}

执行结果:
1,没有异常,返回try块中的值.
2,发生异常,返回catch中的值.
在这里插入图片描述
return在catch{}块里面和在try{}catch{}finally{}代码块外面:

public class DemoTest {
    public static void main(String[] args) {
        int num = getNum();
        System.out.println("执行结果:   " +num);
    }

    public static int getNum() {
        int i;
        try {
            i = 8;
            System.out.println("try块中的i的值:  "+i);
            int a = 90 / 0;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            i = 5;
            return i;// catch了异常之后会在此处返回i的值
        } finally {
            // finally中的代码一定会执行
            System.out.println("执行finally~~~");
            i = 6666;// 此处重新给i赋值
            System.out.println("finally 块中的值:  "+i);
        }
        return i;// 没有异常返回此处的值
    }
}

执行结果:
1,catch住异常之后返回catch{}块中的值.
2,没有异常不会执行catch{}块中的代码,会执行到最后,返回最后的值.

总结:
1,只要finally{}块中有return则一定会返回finally{}块中的值.
2,catch{}块中有return和在finally{}代码块后面有return,执行结果catch住异常之后会直接返回catch{}中的值,没有异常的话会执行最后返回最后的值.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值