Java -- 異常的捕獲及處理 -- Exception類與RuntimeException類

來源:互聯網
上載者:User

標籤:代碼   ack   images   console   java   try   span   img   為什麼   

  7.3 Exception類與RuntimeException類

    Exception類與RuntimeException類的聯絡與區別???

    例:字串變為整型

    Class : RuntimeExceptionDemo01

package limeThrowable._7_3;public class RuntimeExceptionDemo01 {    public static void main(String[] args) {        String str = "123";        int i = Integer.parseInt(str);        System.out.println(i * i);    }}

    Console : 

15129

    其中parseInt()簽名:

public static int parseInt(String s) throws NumberFormatException

    parseInt()方法在聲明時使用了throws關鍵字,但是在方法調用時並沒有使用try---catch進行處理,這是為什嗎?

    觀察NumberFormatException類的繼承關係:

    

    可以發現NumberFormatException屬於RuntimeException的子類,那麼這時就可以清楚地知道:

    ⊙ Exception在程式中必須使用try---catch進行處理。

    ⊙ RuntimeException可以不實用try---catch進行處理,但是如果有異常產生,則異常將由JVM進行處理。

    提示:

      對於RuntimeException的子類最好也使用異常處理機制。

      雖然RuntimeException的異常可以不用try---catch進行處理,但是如果一旦出現異常,則肯定會導致程式中斷執行,所以,為了保證程式在出錯後依然可以執行,所以在開發代碼時最好使用try---catch的異常處理機制進行處理。

 

7.4 自訂異常類

啦啦啦

Java -- 異常的捕獲及處理 -- Exception類與RuntimeException類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.