我们在学习异常的过程中,可以只去写一个异常处理程序来捕获所有类型的异常。
即通过捕获异常类型的基类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);
}
}
}
运行结果:
这个为大家提供一个参考!
谢谢!