生活随笔
收集整理的這篇文章主要介紹了
Java异常处理throws/throw
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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
) {String
[] strs
= {"18","0"};try {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
) {String
[] str1
= {"1"};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) {throw new Exception("參數個數不夠");} if (str0
[1]!=null
&& str0
[1].equals("0")) {throw new RuntimeException("除數不能為0");}int a
= Integer
.parseInt(str0
[0]);int b
= Integer
.parseInt(str0
[1]);int c
= a
/b
;System
.out
.println("結果為:"+c
);}
}
結果如下:
總結
以上是生活随笔為你收集整理的Java异常处理throws/throw的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。