標籤:測試 http 拋出異常 img error 退出 int 類別關係 format
今天在做一個將String轉換為Integer的功能時,發現Integer.parseInte()會拋出異常NumberFormatException.
函數Integer.parseInt(String)定義
1 public static int parseInt(String s)2 throws NumberFormatException
測試代碼:
1 public class Test2 {3 public static void main(String[] args)4 {5 Integer num = Integer.parseInt("ff");6 System.out.println(num);7 }8 }
我們知道,所有的會拋出異常的地方都需要try catch 捕獲,或者使用throws繼續向上拋出。那麼為什麼上面的代碼會通過編譯呢?原來Java裡面有Exception和RuntimeException這兩個類。RuntimeException是Excetpion的子類。如果一個某一個異常是RuntimeException的子類而不是Exception的子類,那麼我們可以不用顯示的try catch捕獲,而是在發生異常的時候拋給JVM捕獲。當然我們也可以寫上try catch來處理,不交給JVM。如下面的代碼:
1 public class Test 2 { 3 public static void main(String[] args) 4 { 5 try 6 { 7 Integer num = Integer.parseInt("ff"); 8 System.out.println(num); 9 }catch(Exception e)10 {11 System.out.println("程式出現了異常!");12 }13 }14 }
關於Java中的異常,還有一些常見問題,現在羅列在下面:
1) Exception類別關係
Throwable是所有異常的父類。如常見的:NullPointerException和ClassNotFoundException
2)Error和Exception
Throwable下有兩個子類,一個是Exception,另一個是Error。那麼Error和Exception有什麼區別呢?
Error:是指JVM錯誤。這個是我們自己寫程式中不會遇到的,是JVM運行過程中自己拋出的異常。這個不需要程式員過多的關注。
Exception:所有使用者可以處理的異常的父類。也就是說,我們寫代碼的過程中可能會遇到的所有的異常的父類就是Exception
3)Exception和RuntimeException
這就是本文一開始討論的話題。Exception是RuntimeException的父類。程式員在寫代碼的時候,如果遇到拋出的是RuntimeException,則可以根據情況選擇是否用try catch或者throws 對異常進行處理。如果遇到的異常是Exception子類,但又不是RuntimeException子類,那麼程式中必須顯示的try catch或者throws 進行處理。
4)throw與throws的區別
throw指的是我們程式遇到異常的時候,在當前上下文中不處理。說得更狹隘一點,比如我們在一個函數中,如果有異常,我們直接用throws拋出,交給函數調用處進行處理,而不在本函數中處理。
throws指的是如果函數中有用throw拋出異常,需要在函式宣告的末尾加上throws語句,表明當前函數會拋出異常,從而通知函數的調用出進行顯式處理。throws和throw是配合使用的。如下面的代碼:
1 public class Test 2 { 3 public static void main(String[] args) 4 { 5 doSomething(); 6 } 7 8 public static void doSomething()throws Exception 9 { 10 Integer num = Integer.parseInt("ff");11 System.out.println(num); 12 }13 }
上面的代碼無法通過編譯,因為在doSomthing()裡面拋出了異常,需要在Main函數中處理。Main函數要麼加上try catch 語句,要麼將此異常繼續向上拋出,交給JVM處理。但一般不這麼做。我們總希望程式能正確的運行並退出。下面是正確的處理異常代碼:
1 public class Test 2 { 3 public static void main(String[] args) 4 { 5 try 6 { 7 doSomething(); 8 } 9 catch(Exception e)10 {11 System.out.println("doSomething函數出現了異常!異常資訊如下:");12 e.printStackTrace();13 }14 System.out.println("Main函數正常退出!");15 }16 17 public static void doSomething()throws Exception18 { 19 Integer num = Integer.parseInt("ff");20 System.out.println(num); 21 }22 }
Java中的異常-Throwable-Error-Exception-RuntimeExcetpion-throw-throws-try catch