Java小细节——try/catch/finally/return不得不说的秘密

阅读2分钟,掌握一个Java小细节,你值得拥有!

java面试经常能看到这道题目:

try {} 里有一个return语句,那么紧跟在这个try后的finally {}里的代码会不会被执行?什么时候被执行?在return前还是后?

try/catch/finally 都有return 语句

public class tryCatchDemo {

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

    public static String testTryCatch(){
        int index = 0;
        try{
            index++;
            return "tryReturn"+index;
        }
        catch (Exception e){
            index = index-10;
            return "catchReturn"+index;
        }
        finally {
            index--;
            return "finallyReturn"+index;
        }
    }
}

这里写图片描述

再看一个例子,注意看执行顺序,非常重要

public class tryCatchDemo {

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

    public static String testTryCatch() {
        int index = 0;
        try {
            index++;
            return "tryReturn" + (++index);
        } catch (Exception e) {
            index = index + 10;
            return "catchReturn" + (++index);
        } finally {
            //index--;
            return "finallyReturn" + index;
        }
    }
}

这里写图片描述

在try和finally中都有return的情况下,会先执行try中return语句,然后执行finally。所以千万得注意到这个执行顺序,会影响到最终得返回值。

try/catch 有return语句

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

    public static String testTryCatch() {
        int index = 0;
        try {
            index++;
            String nullStr = null;
            nullStr.toString();
            return "tryReturn" + (++index);
        } catch (Exception e) {
            index = index + 10;
            return "catchReturn" + (++index);
        } finally {
            System.out.println("finally");
        }
    }

这里写图片描述

无论是try还是catch,都会先执行return语句然后再执行finally。

总结:
1、不管有没有出现异常,finally块中代码都会执行;
2、当try和catch中有return时,finally仍然会执行;
3、finally是在return后面的表达式运算后执行的(此时并没有返回运算后的值,而是先把要返回的值保存起来,不管finally中的代码怎么样,返回的值都不会改变,任然是之前保存的值),所以函数返回值是在finally执行前确定的;
4、finally中最好不要包含return,否则程序会提前退出,返回值不是try或catch中保存的返回值。

finally中最好不要有return,阿里编程规约也约定了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值