1. 程式人生 > >Java 的 catch 塊裡有 return 語句執行時,finally 塊裡的語句會怎麼執行?

Java 的 catch 塊裡有 return 語句執行時,finally 塊裡的語句會怎麼執行?

遇到個很有意思的問題,Java 的 catch 塊裡有 return 語句執行時,finally 塊裡的語句會執行嗎?執行順序是怎樣的?
雖然平時很少這樣寫,但這是個值得思考的問題,這篇部落格就來求證一下。

場景一:return x,返回只有一個引用

public class Test {

    public static void main(String[] args) {
        int back = Test.test();
        System.out.println(back);
    }

    public static int test() {
        int
x = 0; try { throw new Exception(); } catch (Exception e) { return x; } finally { System.out.println("執行finally塊"); } } }

執行上述程式碼,得到結果:

執行finally0

可以看出來先執行的 finally 塊的語句,再返回到呼叫者。

場景二:return x = x + 1,返回的是一個計算賦值語句

對上述程式碼稍做修改:

public class Test {

    public static void main(String[] args) {
        int back = Test.test();
        System.out.println(back);
    }

    public static int test() {
        int x = 0;
        try {
            throw new Exception();
        } catch (Exception e) {
            return x = x + 1;
        } finally
{ System.out.println(x); } } }

執行上述程式碼,得到結果:

1
1

說明先執行的 return 語句 x = x + 1,再執行的finally 塊。

場景三:如果 finally 塊中有對返回值 x 的修改,會返回給呼叫者嗎?

對上述程式碼稍做修改:

public class Test {

    public static void main(String[] args) {
        int back = Test.test();
        System.out.println("呼叫者中 x = " + back);
    }

    public static int test() {
        int x = 0;
        try {
            throw new Exception();
        } catch (Exception e) {
            return x = x + 1;
        } finally {
            x = x - 1;
            System.out.println("finally中 x = " + x);
        }
    }
}

執行上述程式碼,結果如下:

finally中 x = 0
呼叫者中 x = 1

這下有點意思了,finally 塊中的 x = x - 1雖然執行了,但是並沒有影響返回值。這說明在 return 那已經確定並儲存了返回值,finally 塊裡的語句是改變了 x 的值,但並沒有改變要返回的值。