妳應該這樣去理解 “所有“ 的 Exception 類。
在 java 中 java.lang.Exception 是 java.lang.Throwable 的子類,而 java.lang.RuntimeException 也是 java.lang.Throwable 的子類。
因此,如果有壹段代碼,不管是會發生 Exception 還是 RuntimeException ,而妳想壹次性捕獲所有錯誤的時候,這樣寫:
public?static?void?main(String[]?args)?{System.out.println("----------?測試輸出?1?----------");
try{
String?s?=?null; //註:這壹個會拋出?NullPointException,即?RuntimeException的子類。 s?=?s.substring(0);?}catch(Throwable?ex)?{
ex.printStackTrace();}
System.out.println("----------?測試輸出?2?----------");
try{
String?s?=?"123"; //註:這壹個會拋出?IndexOutOfBoundsException,即?RuntimeException?的子類。 int?i?=?s.indexOf(200);?}catch(Throwable?ex)?{
ex.printStackTrace();}
System.out.println("----------?測試輸出?3?----------");
}
妳在上面的代碼裏面可以看到,即使是發生了 RuntimeException ,但是使用了 Throwable 也可以捕獲到,而且妳不用關心具體是什麽原因出錯了,只要有錯誤,用 Throwable 都可捕獲到。
如果不使用 Throwable ,又是壹個什麽情況呢,這個時候,妳就需要在程序中針對某壹個 Exception 或 RuntimeException 來寫 catch 了:
public?static?void?main(String[]?args)?{System.out.println("----------?測試輸出?4?----------");
try{
String?s?=?null; //註:這壹個會拋出?NullPointException,即?RuntimeException?的子類。 s?=?s.substring(0);?}catch(NullPointException?ex)?{
ex.printStackTrace();}
System.out.println("----------?測試輸出?5?----------");
try{
String?s?=?"123"; //註:這壹個會拋出?IndexOutOfBoundsException,即?RuntimeException?的子類。 int?i?=?s.indexOf(200);?}catch(IndexOutOfBoundsException?ex)?{
ex.printStackTrace();}
System.out.println("----------?測試輸出?6?----------");
}
但是,其實所有 RuntimeException 及其子類都不需要在程序中顯式調用的,如果不進行顯式調用,則表明妳不需要理會錯誤,當有任何錯誤發生時,讓程序自動終止:
public?static?void?main(String[]?args)?{System.out.println("----------?測試輸出?7?----------");
String?s?=?null;?
//註:這壹個會拋出?NullPointException,即?RuntimeException?的子類。?
s?=?s.substring(0);
System.out.println("----------?測試輸出?8?----------");
String?s?=?"123";
//註:這壹個會拋出?IndexOutOfBoundsException,即?RuntimeException?的子類。
int?i?=?s.indexOf(200);?
System.out.println("----------?測試輸出?9?----------");}
這個時候,在上面代碼中,因為沒有進行 catch ,所以,第 2 句 “測試輸出 8” 就不會執行到了。