Java的Checked Exception與Runtime Exception

| | Comments (0) | TrackBacks (0)


Java將Exception分成二大部份,一種為「Checked Excepiton」,也就是編譯時會提醒您需要加以處理的Exception,例如以下二行程式,

Class.forName(driver); Connection conn = DriverManager.getConnection(connString,account,password );

其中第一行編譯時或開發工具時(如Escape)會提醒「Unhandled exception type ClassNotFoundException」,第二行則會提醒「 Unhandled exception type SQLException」。只要是這類型的,一般都稱為 Checked Exception 。所以Checked Exception 的特點即有問題要額外處理或則往上層拋例外(throws Exception)。


另一種 Exception 則稱為「Runtime Exception」,顧名思義即在執行週期時才會發生的 Exception,常見的 Runtime Exception 為 NullPointerException。Runtime Excepiton 的特點與 Checked Exception 剛好相反,不需在開發週期強制放 try-catch 區段或則往上層拋例外(throws Exception)。


接下來看看以下的範例,method1 & method3 皆為典型的 Checked Excepiton、method2 則為 Runtime Exception。

class CheckedException extends Exception{ public CheckedException() {} public CheckedException(String msg){ super(msg); } } class ExceptionalClass{ // checked exception public void method1(String msg) throws CheckedException { throw new CheckedException("checkException拋出來的Exception!!"); } // runtime exception public void method2(String msg){ if (msg == null) { throw new RuntimeException("Message is null !!"); } } // checked exception public void method3(String msg) throws CheckedException{ method1(msg); } } public class ExceptionTest { public static void main(String[] args) { ExceptionalClass example = new ExceptionalClass(); try { example.method1(null); example.method3(null); } catch(CheckedException ex){ ex.printStackTrace(System.out); } example.method2(null); System.out.println("Program run done!!"); } }

至於自行開發底層元件時,到底要用 Checked Exception 還是 Runtime Exception 實際上看需求或喜好而定。但就個人角度來看,雖然 Checked Exception 看似比較能掌握例外,但是過多的 Checked Exception 的處理,會降低程式的可讀性。所以應該還是看狀況來決定例外處理方式。

0 TrackBacks

Listed below are links to blogs that reference this entry: Java的Checked Exception與Runtime Exception.

TrackBack URL for this entry: http://blog.db.idv.tw/cgi-bin/mt/mt-tb.cgi/54

Leave a comment