JavaSE程序分析002 try-catch-finally與return的小事情

程序段如下:

class Test
{
    public static String output = "";
    public static void foo(int i)
    {
        try
        {
            if (i == 1)
                throw new Exception();
            output += "1";
        }
        catch (Exception e)
        {
            output += "2";
            return;
        }
        finally
        {
            output += "3";
        }
        output += "4";
    }
    public static void main(String[] args)  
    {
        foo(0);
        System.out.println(output);
        foo(1);
        System.out.println(output);
    }
}

執行結果如下:
此程序段的執行結果

分析:try-catch-finally程序塊是一個整體,當執行catch裏面的return之後,finally裏面的代碼塊也是要執行的。

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