Exception Handling

Try - Catch with Resource

Java 7 以前

需要使用 try-catch-finally 進行資源的關閉。

Java 7 以後

自動關閉資源,透過實作 java.lang.AutoCloseable 介面來使用其包含的 close 方法。

可以同時關閉多個資源,透過 " ; " 區隔,越後面撰寫的物件越早關閉

Suppressed Exceptions

Java 7 以前

若一個例外被 catch 之後在catch 或 finally 階段又發生了例外,通常會拋出第一個錯誤,第二個則會被抑制( suppressed )。

Java 7 以後

使用 .addSuppressed() 方法,可以將第二個例外記錄在第一個例外之中。

相對應的方法是 .getSuppressed() 方法,取得 Throwable[] 參數,代表曾紀錄的錯誤。

public static void main(String[] arguments) throws Exception{
    try{
        memberFunction();
        
    }catch(Exception ex){
        err.println("Exception encountered: " + ex.toString());
        final Throwable[] suppressedExceptions = ex.getSuppressed();
        final int numSuppressed = suppressedExceptions.length;
        
        if (numSuppressed > 0){
            err.println("tThere are " + numSuppressed + " suppressed exceptions:");
            for (final Throwable exception : suppressedExceptions){
                err.println("tt" + exception.toString());
            }
        }
    }
}

//編譯後,發生錯誤顯示 log

//Exception encountered: java.lang.NullPointerException: XXX
//There are 1 suppressed exceptions:
//        java.lang.RuntimeException: XXX
public static void memberFunction() throws Exception{
    Throwable th = null;
    DirtyResource resource= new DirtyResource();
    try{
        resource.accessResource();
    }catch(Exception e) {
        th = e;
    }finally{
        try{
            resource.close();
        }catch(Exception e){
            if(th != null){
                e.addSuppressed(th); //Add to primary exception
                throw e;
            }
        }
    }
}

Multi Catch

Java 7 以前

catch 中,只能一次捕捉一個例外。

Java 7 以後

catch 中 可以透過 " | " 字符,區隔的例外不可以有 繼承 的行為。

Last updated

Was this helpful?