一、finally执行的情况
在讨论return和finally的关系之前,先了解finally的执行情况。在Java中,finally块一定会执行,无论try、catch块中的代码是否抛出了异常,也无论有没有return语句。当在try、catch块中有return语句时,finally总是在return之前执行,这意味着finally可以用来释放资源、关闭连接等操作。下面是一个简单的示例:
public class FinallyDemo {
    public static void main(String[] args) {
        System.out.println(getNumber());
    }
    public static int getNumber() {
        int num = 1;
        try{
            num++;
            int result = 10 / 0;
            return num;
        }catch(Exception e){
            num++;
            return num;
        }finally{
            num++;
            System.out.println("finally执行了!");
        }
    }
}
输出结果为:
finally执行了!
3
可以看到,finally块最后执行并输出了内容,同时返回值为3,而不是try、catch块中的返回值。
二、finally对于return语句的影响
在上面的例子中,我们看到了finally块对于返回值的影响。如果在try块中有return语句,在执行finally块之前,该return已经执行完毕,而如果finally块也有return语句,就会取代之前的return语句。
public class FinallyReturnDemo {
    public static void main(String[] args) {
        System.out.println(getNumber());
    }
    public static int getNumber() {
        int num = 1;
        try{
            num++;
            int result = 10 / 0;
            return num;
        }catch(Exception e){
            num++;
            return num;
        }finally{
            num++;
            System.out.println("num的值为:"+num);
            return 999;
        }
    }
}
输出结果为:
num的值为:3
999
我们可以看到,虽然在try、catch块中都有return语句,但是因为finally块中有return语句,最后返回的值是999而不是try、catch块中的2或3。
三、如何避免finally影响return的结果
虽然finally对于代码块的执行情况有保障,但是对于return语句的处理,会带来一定的不确定性。为了避免finally对于return语句的影响,可以采用一些技巧。一种方法是避免在finally块中使用return语句,而是使用一个变量来存储返回值,最后在finally块之外返回该变量:
public class FinallyReturnDemo2 {
    public static void main(String[] args) {
        System.out.println(getNumber());
    }
    public static int getNumber() {
        int num = 1;
        int result = 0;
        try{
            num++;
            int count = 10 / 0;
            result = num;
        }catch(Exception e){
            num++;
            result = num;
        }finally{
            num++;
            System.out.println("num的值为:"+num);
        }
        return result;
    }
}
输出结果为:
num的值为:3
3
这样,在finally块中对于返回值的修改并不会影响返回的结果,而且代码也更加可读。
四、总结
在Java中,finally块总是会执行,无论try、catch块中的代码是否抛出了异常,也无论有没有return语句。在try、catch块中有return语句时,finally块总是在return之前执行,如果finally块中有return语句,就会取代之前的return语句,产生一定的不确定性。为了避免finally对于return语句的影响,可以采用避免在finally块中使用return语句、使用一个变量来存储返回值等方法。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/305086.html
 
 微信扫一扫
微信扫一扫  支付宝扫一扫
支付宝扫一扫 