標籤: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