天天看点

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 = ;
        try{
            index++;
            return "tryReturn"+index;
        }
        catch (Exception e){
            index = index-;
            return "catchReturn"+index;
        }
        finally {
            index--;
            return "finallyReturn"+index;
        }
    }
}
           
Java小细节——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 = ;
        try {
            index++;
            return "tryReturn" + (++index);
        } catch (Exception e) {
            index = index + ;
            return "catchReturn" + (++index);
        } finally {
            //index--;
            return "finallyReturn" + index;
        }
    }
}
           
Java小细节——try/catch/finally/return不得不说的秘密

在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 = ;
        try {
            index++;
            String nullStr = null;
            nullStr.toString();
            return "tryReturn" + (++index);
        } catch (Exception e) {
            index = index + ;
            return "catchReturn" + (++index);
        } finally {
            System.out.println("finally");
        }
    }
           
Java小细节——try/catch/finally/return不得不说的秘密

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

总结:

1、不管有没有出现异常,finally块中代码都会执行;

2、当try和catch中有return时,finally仍然会执行;

3、finally是在return后面的表达式运算后执行的(此时并没有返回运算后的值,而是先把要返回的值保存起来,不管finally中的代码怎么样,返回的值都不会改变,任然是之前保存的值),所以函数返回值是在finally执行前确定的;

4、finally中最好不要包含return,否则程序会提前退出,返回值不是try或catch中保存的返回值。

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