[轉]Unchecked Exception 和 Checked Exception 比較

來源:互聯網
上載者:User

標籤:

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 比較

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.