我們在學習異常的過程中,可以只去寫一個異常處理程序來捕獲所有類型的異常。
即通過捕獲異常類型的基類Exception就可以做到這一點:
catch(Exception e){
System.out.println("Caught an exception");
}
這樣我們將捕獲所有異常,所以最好將它放在處理程序列表的末尾,以防止它搶在其他處理程序之前先把異常捕獲了。
下面用一個程序來演示:
public class ExceptionMethods {
public static void main(String[] args) {
try{
throw new Exception("My Exception");
}catch(Exception e){
System.out.println("Caught Exception");
System.out.println("getMessage():"+e.getMessage());
System.out.println("getLocalizedMessage():"+
e.getLocalizedMessage());
System.out.println("toString()"+e);
System.out.println("printStackTrace():");
e.printStackTrace(System.out);
}
}
}
運行結果:
這個爲大家提供一個參考!
謝謝!