先贴一段代码
// This program creates a custom exception type.
class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
}
}
结果
Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]
现在我们来分析这段代码
①调用compute(1), 输出Called compute(1)
②if判断,不满足条件,
③接着输出 Normal exit
④返回主函数,调用compute(20),输出Called compute(20)
⑤满足if判断,抛出异常,进入到自己创建的异常中,detail=a;
⑥回到throw new MyException(a);结束,返回到主函数。
⑦捕获抛出的异常,打印输出Caught MyException[20]
注意:⑦没有调用MyException的toString方法,为何能打印出结果?
分析:在Java中,所有的对象都是继承自Object,自然继承了toString方法,在当使用System,out.println()里面为一个对象的引用时,自动调用toString方法讲对象打印出来。如果重写了tostring方法则调用重写的toString 方法。