
class MyException extends Exception {
public MyException() {}
public MyException(String msg) {
super(msg);
}
}
public class Demo3 {
public static void main(String[] args) {
try {
test();
} catch (MyException e) {
System.out.println("Catch My Exception");
e.printStackTrace();
}
}
public static void test() throws MyException{
try {
int i = 10/0;
System.out.println("i="+i);
} catch (ArithmeticException e) {
throw new MyException("This is MyException");
}
}
}
读者可对该段程序的输出做一个判断。
答案是:先是执行test方法中的除0异常,被test的catch捕获之后又抛出了一个Exception的子类MyException,其内容是让父类调用,参数为
"This is MyException"的字符串(在打印追踪栈的时候显示),然后回到mian方法被main函数的catch捕获了,并输出
“Catch My Exception"之后输出错误所在位置,同时显示了"This is MyException”
PS:Throwable包含了其线程创建时线程执行堆栈的快照,它提供了printStackTrace()等接口用于获取堆栈跟踪数据等信息。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)