JAVA丟擲異常的三種形式
一、系統自動丟擲異常
當程式語句出現一些邏輯錯誤、主義錯誤或者型別轉換錯誤時,系統會自動丟擲異常
例一
public static void main(String[] args) {
int a = 5;
int b = 0;
System.out.println( a / b);
}
執行結果,系統會自動丟擲ArithmeticException
異常
Exception in thread "main" java.lang.ArithmeticException: / by zero
at io.renren.modules.sys.controller.SysUserController. main(SysUserController.java:154)
例二
public static void main(String[] args) {
String str = "abc";
System.out.println(Integer.parseInt(str));
}
執行結果,系統會丟擲NumberFormatException
異常
Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
at java.lang.NumberFormatException. forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at io.renren.modules.sys.controller.SysUserController.main(SysUserController.java:153)
二、throw
throw是語句丟擲一個異常,一般是在程式碼的內部,當程式出現某種邏輯錯誤時同程式主動丟擲某種特定型別的異常
public static void main(String[] args) {
String str = "NBA";
if (str.equals("NBA")) {
throw new NumberFormatException();
} else {
System.out.println(str);
}
}
執行結果,系統會丟擲NumberFormatException
異常
Exception in thread "main" java.lang.NumberFormatException
at io.renren.modules.sys.controller.SysUserController.main(SysUserController.java:154)
三、throws
throws是方法可能會丟擲一個異常(用在宣告方法時,表示該方法可能要丟擲異常)
public void function() throws Exception{......}
當某個方法可能會丟擲某種異常時用於throws 宣告可能丟擲的異常,然後交給上層呼叫它的方法程式處理
public static void testThrows() throws NumberFormatException {
String str = "NBA";
System.out.println(Integer.parseInt(str));
}
public static void main(String[] args) {
try {
testThrows();
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("非數直型別不能強制型別轉換");
}
}
執行結果
java.lang.NumberFormatException: For input string: "NBA"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at io.renren.modules.sys.controller.SysUserController.testThrows(SysUserController.java:153)
at io.renren.modules.sys.controller.SysUserController.main(SysUserController.java:158)
非數直型別不能強制型別轉換
throw與throws的比較
1、throws出現在方法函式頭,而throw出現在函式體。
2、throws表示出現異常的一種可能性,並不一定會發生這些異常,throw則是丟擲了異常,執行throw則一定丟擲了某種異常物件。
3、兩者都是消極處理異常的方式(這裡的消極並不是說這種方式不好),只是丟擲或者可能丟擲異常,但不會由函式去處理異常,真正的處理異常由函式的上層呼叫處理。
程式設計習慣
1、在寫程式時,對可能會出現異常的部分通常要用try{…}catch{…}去捕捉它並對它進行處理;
2、用try{…}catch{…}捕捉了異常之後一定要對在catch{…}中對其進行處理,那怕是最簡單的一句輸出語句,或棧輸入e.printStackTrace();
3、如果是捕捉IO輸入輸出流中的異常,一定要在try{…}catch{…}後加finally{…}把輸入輸出流關閉;
4、如果在函式體內用throw丟擲了某種異常,最好要在函式名中加throws拋異常宣告,然後交給呼叫它的上層函式進行處理。