異常的定義:阻止當前方法或作用域繼續執行的情況,即程序無法正常執行下去稱之為異常。
異常的基本結構:
所有不正常的類都繼承與Throwable類,包括Error類和Exception類
Error一般是JVM拋出的錯誤,比如StackOverFlowError,OutOfMemoryError,這些錯誤是無法挽回的,只能結束當前Java進程的執行;
Exception異常是Java應用拋出的,分為編譯時期可檢測的異常(如IOException)和運行時期的異常(NullPointerException)
編譯時期可檢測的異常必須要處理,否則編譯器會報錯誤,
運行時期的異常RuntimeException不需要強制處理,Exception異常一般可以通過捕獲處理以后,程序可以繼續正常執行。
java異常常用的解決語句:
栗子一:
try catch finally 語句:
public static void main(String[] args) { int []arr=new int[5]; try { arr[5]=0; System.out.println(5); }catch (ArrayIndexOutOfBoundsException e){ System.out.println("下標越界啦!"); System.out.println("e.getMessage()"+e.getMessage()); System.out.println("e.getCause()"+e.getCause()); System.out.println("e.toString()"+e.toString()); }finally {
System.out.println("finally執行了");
}
}
運行結果:
下標越界啦! e.getMessage()5 e.getCause()null e.toString()java.lang.ArrayIndexOutOfBoundsException: 5
finally執行了
try語句塊通常包括可能發生異常的代碼,try語句塊發生異常時,不再繼續執行,try語句不能單獨使用
catch用來捕獲異常並且發出警告:提示、檢查配置、網絡連接,記錄錯誤等。
每一個catch塊用於處理一個異常。異常匹配是按照catch塊的順序從上往下尋找的,只有第一個匹配的catch會得到執行。匹配時,不僅運行精確匹配,也支持父類匹配,因此,如果同一個try塊下的多個catch異常類型有父子關系,應該將子類異常放在前面,父類異常放在后面,這樣保證每個catch塊都有存在的意義。
finally最終執行的代碼,用於關閉和釋放資源。
異常的常用方法:
e.toString()獲取的信息包括異常類型和異常詳細消息,
e.getCause()獲取產生異常的原因
e.getMessage()只是獲取了異常的詳細消息字符串。
栗子二:
throw是用於拋出異常。
public static void main(String[] args) { int[] arr = new int[5]; int i = 5; if (i > arr.length - 1) throw new ArrayIndexOutOfBoundsException("數組下標越界"); System.out.println(arr[i]); } }
throws用在方法簽名中,用於聲明該方法可能拋出的異常,方法的調用者來處理異常
public static void main(String[] args) { try { test(); }catch (Exception e){ System.out.println("捕獲異常"); } } private static void test() throws ArrayIndexOutOfBoundsException{ int[] arr = new int[5]; int i = 5; if (i > arr.length - 1) throw new ArrayIndexOutOfBoundsException("數組下標越界"); System.out.println(arr[i]); }
注意的點: 1、不管有木有出現異常或者try和catch中有返回值return,finally塊中代碼都會執行;
2、finally中最好不要包含return,否則程序會提前退出,返回會覆蓋try或catch中保存的返回值。
3. 如果方法中try,catch,finally中沒有返回語句,則會調用這三個語句塊之外的return結果
4. 在try語句塊或catch語句塊中執行到System.exit(0)直接退出程序