JAVA學習日記day5

來源:互聯網
上載者:User

標籤:java學習日記

1.通過一個簡單的例子示範一下異常。

1.  字串轉換成整數

  Integer 是 int 的封裝類。

  Exception in thread "main" java.lang.NumberFormatException: For input string: "hello"    在主方法中程式出現異常,錯誤資訊是數字格式異常:輸入的字串hello

  錯誤堆棧資訊

650) this.width=650;" src="/e/u261/themes/default/images/spacer.gif" style="background:url("/e/u261/lang/zh-cn/images/localimage.png") no-repeat center;border:1px solid #ddd;" alt="spacer.gif" />

錯誤出現在main函數的第7行代碼中

  異常,例外  線程(程式)

【解決方案】為了避免這種錯誤,我們用try...catch解決

 try塊中,是可能會引起錯誤的代碼

 catch塊中,是發生錯誤以後,需要執行的代碼。

  有的錯誤必須要處理。

650) this.width=650;" src="/e/u261/themes/default/images/spacer.gif" style="background:url("/e/u261/lang/zh-cn/images/localimage.png") no-repeat center;border:1px solid #ddd;" alt="spacer.gif" />

  Unhandled exception type ClassNotFoundException  沒處理的異常:類沒找到錯誤

 解決辦法:1.surround 包圍  用try ...catch

2.throws  扔掉不處理

第二節

2.什麼是異常

  程式運行中出現的,導致程式無法正常啟動並執行錯誤,叫做異常

異常的父類Throwable

 Ctrl  + T 顯示繼承關係

 Throwable 主要有兩個子類

 1.Error (一般是JVM運行中出現了問題,不用處理,也沒法處理) JVM=Java Virtual Machine 虛擬機器

 2.Exception

   子類分為兩種,其中一種叫做RuntimeException(又有很多子類,也不用管),這種錯誤可以處理,也可以不處理。

   另外一種叫做非RuntimeException(好幾百種,不用管)

  RuntimeException 可以try catch,也可以不try catch

  非RuntimeException  必須的try catch

  示範類的繼承關係圖。

RuntimeException

1.NullPointerException(null 指標異常)

2.IndexOutOfBoundsException(數組下標越界異常) ArrayIndexOutOfBoundsException【舉例如下】

650) this.width=650;" src="/e/u261/themes/default/images/spacer.gif" style="background:url("/e/u261/lang/zh-cn/images/localimage.png") no-repeat center;border:1px solid #ddd;" alt="spacer.gif" />

3.NumberFormatException(資料格式異常)

4.ClassCastException(類型轉換異常)

5.IllegalArgumentException(非法參數異常)

6.ArithmeticException(算術異常)

7.IllegalStateException(非法語句異常)

非RuntimeException

ClassNotFoundException(類找不到異常)

第三節

3.拋出異常與處理異常

 try catch finally

 以及多個catch塊的情況

4.自訂異常

 用處不大,暫不講解。


JAVA學習日記day5

聯繫我們

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