java try return 和finally return 執行順序證明

package demo;

public class FinallyReturnDemo {

    static int x = 0;

    public static void main(String[] args) {
        System.out.println("demo1(): " + demo1());// demo1(): 8
        // 正常執行try的return先執行,再執行finally的return並返回

        // 重置
        x = 0;

        System.out.println("demo2(): " + demo2());// demo2(): 3
        // 這個比較好懂,不解析了
    }

    // 正常執行,這個好多人搞混
    public static int demo1() {
        try {
            return x = x + 5;
        } catch (Exception e) {

        } finally {
            System.out.println("demo1 finally");
            return x = x + 3;
        }

    }

    // try代碼塊捕獲異常,這個比較好理解
    public static int demo2() {
        try {
            System.out.println(1 / 0);
            return x = x + 5;
        } catch (Exception e) {
            System.out.println("demo2 catch");
            return x = x + 2;
        } finally {
            System.out.println("demo2 finally");
            return x = x + 3;
        }

    }

}
//demo1 finally
//demo1(): 8
//demo2 catch
//demo2 finally
//demo2(): 5

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章