Java的異常被分為兩大類:Checked異常和Runtime異常(運行時異常)。
? Runtime異常:所有的RuntimeException類及其子類的實例;
? Checked異常:不是RuntimeException類及其子類的異常實例。
只有Java語言提供了Checked異常,其他語言都沒有提供Checked異常。Java認為 Checked異常都是可以被處理(修復)的異常,所以Java程序必須顯式處理Checked 異常。如果程序沒有處理Checked異常,該程序在編譯時就會發生錯誤,無法通過編譯。
Checked異常體現了Java的設計哲學:沒有完善錯誤處理的代碼根本就不會被執行!
Runtime異常則更加靈活,Runtime異常無須顯式聲明拋出,如果程序需要捕獲 Runtime異常,也可以使用try…catch塊來實現。
一.使用throws拋出異常
使用throws聲明拋出異常的思路是,當前方法不知道如何處理這種類型的異常,該異常應該由上級調用者處理;如果main方法也不知道如何處理這種類型的異常,也可以使用throws聲明拋出異常,該異常將交給JVM處理。JVM對異常的處理方法是,打印 異常的跟蹤棧信息,并中止程序運行。
如下示例:
public class ThrowsDemo {public static void main(String[] args) {//throws Exception 虛擬機在處理// 數組索引越界 ArrayIndexOutOfBoundsException//String[] strs = {"1"};// 數字格式異常 NumberFormatException//String[] strs = {"1.8,1"};// 算術異常(除零) ArithmeticExceptionString[] strs = {"18","0"};//intDivide(strs);//虛擬機在處理try {//當 main 方法也不想處理,把異常拋出去,就是java 虛擬機在處理intDivide(strs);} catch (Exception e) {System.out.println("main 異常處理");e.printStackTrace();} } public static void intDivide(String[] strs)throws ArrayIndexOutOfBoundsException,IndexOutOfBoundsException,NumberFormatException,ArithmeticException{ int a = Integer.parseInt(strs[0]);int b = Integer.parseInt(strs[1]);int c = a/b; System.out.println("結果是:"+c); }
}
結果如下:
二.使用throw拋出異常
Java也允許程序自行拋出異常,自行拋出異常使用throw語句來完成(注意此處的 throw沒有后面的s)。
如果需要在程序中自行拋出異常,則應使用throw語句,throw語句可以單獨使用, throw語句拋出的不是異常類,而是一個異常實例,而且每次只能拋出一個異常實例。
如下示例:
public class ThrowDemo {public static void main(String[] args) {//數組索引越界 ArrayIndexOutOfBoundsExceptionString[] str1 = {"1"};// 數字格式異常 NumberFormatException//String[] str2 = {"1.8,1"};// 算術異常(除零) ArithmeticException//String[] str3 = {"18","0"}; try {intDivide(str1);} catch (Exception e) {e.printStackTrace();} } public static void intDivide(String[] str0) throws Exception{ try {int a = Integer.parseInt(str0[0]);int b = Integer.parseInt(str0[1]);int c = a/b;System.out.println("結果是:"+c); }catch (ArrayIndexOutOfBoundsException e) {throw new Exception("數組索引越界");}catch (IndexOutOfBoundsException e) {throw new Exception("索引越界");}catch (NumberFormatException e) {throw new Exception("數字轉換失敗");}catch (ArithmeticException e) {throw new Exception("計算錯誤");} catch (Exception e) {System.out.println("其他異常");e.printStackTrace();} if (str0.length<2) {//自行拋出 Exception異常//該代碼必須處于try塊里,或處于帶 throws聲明的方法中throw new Exception("參數個數不夠");} if (str0[1]!=null && str0[1].equals("0")) {//自行拋出 RuntimeException異常,既可以顯式捕獲該異常//也可完全不理會該異常,把該異常交給該方法調用者處理throw new RuntimeException("除數不能為0");}int a = Integer.parseInt(str0[0]);int b = Integer.parseInt(str0[1]);int c = a/b;System.out.println("結果為:"+c);}
}
結果如下: