关于java exception的一个小问题…

06-12-22 wilson751

有如下一小段程序:

异常基类

public class BaseException extends Exception {

protected Throwable rootCause = null;

protected BaseException() {}

protected BaseException(Throwable rootCause) {

this.rootCause = rootCause;

}

public Throwable getRootCause() {

return this.rootCause;

}

public void setRootCause(Throwable rootCause) {

this.rootCause = rootCause;

}

public void printStackTrace() {

printStackTrace(System.err);

}

public void printStackTrace(PrintStream out) {

printStackTrace(new PrintWriter(out));

}

public void printStackTrace(PrintWriter writer) {

super.printStackTrace(writer);

//输出原始异常

if(getRootCause() != null) {

//e.printStackTrace(..);

getRootCause().printStackTrace(writer);

}

writer.flush();

}

}

异常子类

public class UploadException extends BaseException {}

模拟的接口类:

public class InterfaceClass {

public void test() throws UploadException {

try {

throw new IOException();

}catch(IOException ioe) {

//log the original exception

UploadException ue = new UploadException();

ue.setRootCause(ioe);

throw ue;

}

}

}

前端程序:

public class ClientClass {

public static void main(String[] args) {

try{

new InterfaceClass().test();

}catch(UploadException ue) {

ue.printStackTrace();

}

}

}

当执行ClientClass时,到new InterfaceClass().test();时,InterfaceClass的test()方法抛出IOException异常,被catch后,包装为BaseException的子类UploadException,最后在ClientClass的main()方法中被捕捉:ue.printStackTrace();,运行后得到的结果是:

org.test.util.exception.UploadException

[java] at org. test.util.exception.InterfaceClass.test(InterfaceClass.java:13)

[java] at org. test.util.exception.ClientClass.main(ClientClass.java:6)

[java] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

[java] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

[java] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

[java] at java.lang.reflect.Method.invoke(Method.java:324)

java.io.IOException

[java] at org. test.util.exception.InterfaceClass.test(InterfaceClass.java:9)

[java] at org. test.util.exception.ClientClass.main(ClientClass.java:6)

[java] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

[java] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

[java] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

[java] at java.lang.reflect.Method.invoke(Method.java:324)

输出UploadException,这点我能理解,可以为什么java.io.IOException也被输出呢?它仅仅是

UploadException的一个属性而已,请各位指点迷津,多谢!