我真的很难理解异常处理是如何工作的。为什么最好为我自己的用户定义的异常扩展Exception而不是Throwable类?
try {
//some SQL exception
}
catch(SQLException e) {
System.out.println(e);
}
什么是e真正代表了这里?我知道它是对 SQL 异常对象的引用,但它会打印什么?它会调用toString方法吗?
编辑:当我覆盖该toString方法和从我的源代码中完全删除它时,我得到的输出非常不同。请解释为什么?
class MyException extends Throwable {
private int detail;
MyException(String msg) {
super(msg);
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException { // cant be thrown as throwable
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException("MyException class error");
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
}
}
青春有我
德玛西亚99
相关分类