iT邦幫忙

0

[Java] finally Keyword

閱讀時間: 10分鐘

在學習Java時,相信都會看過finally這個關鍵字。
而它與final同樣也是屬於Java中的保留字,所以不能用作識別字(identifier)。
finally的作用是配合try/catch block使用,以保證在finally的block內的代碼會被執行,
即使遇到exception的情況。

我會用例子加以說明:
有Exception,但沒有處理

class Martin{ 
public static void main(String args[]) 
{ 
    //Method A 
    static void A() 
    { 
        try { 
            System.out.println("顯示A"); 
            throw new Exception(); 
            //沒有處理Exception
        } 
        finally
        { 
            System.out.println("A finally"); 
        } 
     } 
}

有Exception,會被處理

class Martin{ 
public static void main(String args[]) 
{ 
    //Method B 
    static void B() 
    { 
        try { 
            System.out.println("顯示B"); 
            throw new Exception(); 
        } 
        catch (Exception e)
        { 
            System.out.println("Exception caught"); 
        } 
        finally
        { 
            System.out.println("B finally"); 
        } 
    } 
}

在try block內出現return

class Martin{ 
public static void main(String args[]) 
{ 
    // Method C
    static void C() 
    { 
        try { 
            System.out.println("顯示C"); 
            return; 
			//直接return,結束這個method
        } 
        finally
        { 
            System.out.println("C finally"); 
        } 
    } 
}

在catch block內出現return

class Martin{ 
public static void main(String args[]) 
{ 
    //Method D 
    static void D() 
    { 
        try { 
            System.out.println("顯示D"); 
        } 
catch (Exception e)
{ 
            System.out.println("D catch");
    		return;
        } 
        finally
        { 
            System.out.println("D finally"); 
        } 
    } 
}

從例子可以看到不管在什麼情況,在finally內的block的代碼都會被執行。
只有在整個操作系統停止時,才會不被執行。


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言