finally中不要使用return的两种情况

以下两种情况要避免在finally中使用return

1. 如果catch块中捕获了异常,并将该异常throw给上级调用者处理,但finally中return了,那么catch块中的throw就失效了,上级方法调用者是捕获不到异常的

   例: 如下代码上级调用者是捕获不到异常的

public static void main(String[] args){
        try {
            System.out.println(work());
        }catch (Exception e){
            //捕获不到异常
            e.printStackTrace();
        }
    }


    public static int work(){
        int c = 0;
        try{
            c = 3/0;
        }catch (Exception e){
            //除以0 ,会有异常:ArithmeticException: / by zero
            throw e;
        } finally {
            return c;
        }
    }

 

2 . 在finally里的return之前执行了其他return ,最终的返回值还是finally中的return

例 : 如下代码返回的是finally里return的5

public static void main(String[] args){
        System.out.println(work());
    }


    public static int work(){
        int x =3;
        try{
            return x;
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            x = 5;
            return x;
        }
    }

 

 

转载于:https://www.cnblogs.com/kiko2014551511/p/11558346.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值