標籤:
Throwable類是所有異常的始祖,它有兩個直接子類Error / Exception:
Error僅在Java虛擬機器中發生動態串連失敗或其它的定位失敗的時候拋出一個Error對象。一般程式不用捕捉或拋出Error對象。
Unchecked Exception:
a. 指的是程式的瑕疵或邏輯錯誤,並且在運行時無法恢複。
b. 包括Error與RuntimeException及其子類,如:OutOfMemoryError, UndeclaredThrowableException, IllegalArgumentException, IllegalMonitorStateException, NullPointerException, IllegalStateException, IndexOutOfBoundsException等。
c. 文法上不需要聲明拋出異常。
Checked Exception:
a. 代表程式不能直接控制的無效外界情況(如使用者輸入,資料庫問題,網路異常,檔案丟失等)
b. 除了Error和RuntimeException及其子類之外,如:ClassNotFoundException, NamingException, ServletException, SQLException, IOException等。
c. 需要try catch處理或throws聲明拋出異常。
有點困惑的是:RuntimeException (Unchecked)是Exception (Checked)的子類。
樣本:
1 public class GenericException extends Exception {2 public GenericException() {3 }4 5 public GenericException(String message) {6 super(message);7 }8 }
1 public class TestException { 2 public void first() throws GenericException { 3 throw new GenericException("Generic exception"); // Checked Exception需要顯式聲明拋出異常或者try catch處理 4 } 5 6 public void second(String msg) { 7 if (msg == null) 8 throw new NullPointerException("Msg is null"); // Unchecked Exception文法上不需要處理 9 }10 11 public void third() throws GenericException {12 first(); // 調用有Checked Exception拋出的方法也需要try catch或聲明拋出異常13 }14 15 public static void main(String[] args) {16 TestException test = new TestException();17 try {18 test.first();19 } catch (GenericException e) {20 e.printStackTrace();21 }22 23 test.second(null);24 }25 }
[轉]Unchecked Exception 和 Checked Exception 比較