如果只是把当前的异常对象重新抛出,那么printStackTrace()方法显示的将是原来异常抛出点的调用栈信息,而并非重新抛出点的信息。要想更新这个信息,可以使用fillInStackTrace()方法,这将返回一个Throwable对象,他是通过把当前调用栈信息填入原来的那个异常对象而建立的。如下代码所示:
public class Rethowing {
public static void f() throws Exception {
System.out.println("originating the exception in f()");
throw new Exception("throw from f()");
}
public static void g() throws Exception {
try {
f();
} catch (Exception e) {
System.out.println("Inside g(),e.printStackTrace()");
e.printStackTrace(System.out);
throw e;
}
}
public static void h() throws Exception {
try {
f();
} catch (Exception e) {
System.out.println("Inside h(),e.printStackTrace()");
e.printStackTrace(System.out);
throw (Exception) e.fillInStackTrace();
}
}
public static void main(String[] args) {
try {
g();
} catch (Exception e) {
System.out.println("main: printStackTrace()");
e.printStackTrace(System.out);
}
System.out.println("--------");
try {
h();
} catch (Exception e) {
System.out.println("main: printStackTrace()");
e.printStackTrace(System.out);
}
}
}
输入如下:
originating the exception in f()
Inside g(),e.printStackTrace()
java.lang.Exception: throw from f()
at chapter12.t1.Rethowing.f(Rethowing.java:6)
at chapter12.t1.Rethowing.g(Rethowing.java:11)
at chapter12.t1.Rethowing.main(Rethowing.java:31)
main: printStackTrace()
java.lang.Exception: throw from f()
at chapter12.t1.Rethowing.f(Rethowing.java:6)
at chapter12.t1.Rethowing.g(Rethowing.java:11)
at chapter12.t1.Rethowing.main(Rethowing.java:31)
--------
originating the exception in f()
Inside h(),e.printStackTrace()
java.lang.Exception: throw from f()
at chapter12.t1.Rethowing.f(Rethowing.java:6)
at chapter12.t1.Rethowing.h(Rethowing.java:21)
at chapter12.t1.Rethowing.main(Rethowing.java:38)
main: printStackTrace()
java.lang.Exception: throw from f()
at chapter12.t1.Rethowing.h(Rethowing.java:25)
at chapter12.t1.Rethowing.main(Rethowing.java:38)
对比main方法中两次方法调用,可以发现调用fillInStackTrace()的那一行成了异常发生的。