调用printStackTrace方法后调用fillInStackTrace方法

时间:2011-11-29 03:53:46

标签: java exception

Blow是从Java 4版本的Think中复制的一个例子

   public class Rethrowing {
        public static void f() throws Exception {
            System.out.println("originating the exception in f()");
            throw new Exception("thrown from f()");
        }

        public static void h() throws Exception {
            try {
                f();
            } catch (Exception e) {
                System.out.println("Inside h(),e.printStackTrace()");
                e.printStackTrace(System.out); //first print line           throw (Exception) e.fillInStackTrace();
            }
        }

        public static void main(String[] args) {
            try {
                h();
            } catch (Exception e) {
                System.out.println("main: printStackTrace()");
                e.printStackTrace(System.out);
            }
        }
    }


Output:
originating the exception in f()
Inside h(),e.printStackTrace()
java.lang.Exception: thrown from f()
    at Rethrowing.f(Rethrowing.java:20)
    at Rethrowing.h(Rethrowing.java:25)
    at Rethrowing.main(Rethrowing.java:35)
main: printStackTrace()
java.lang.Exception: thrown from f()
    at Rethrowing.f(Rethrowing.java:20)
    at Rethrowing.h(Rethrowing.java:25)
    at Rethrowing.main(Rethrowing.java:35)

When comment //first print line

Output:
originating the exception in f()
Inside h(),e.printStackTrace()
main: printStackTrace()
java.lang.Exception: thrown from f()
    at Rethrowing.h(Rethrowing.java:29)
    at Rethrowing.main(Rethrowing.java:35)

我的问题是为什么我首先在​​fillInStackTrace mehod之前调用e.printStackTrace(printOut out)方法,然后fillInStackTrace似乎不可用。任何人都可以为我做好事,谢谢你提前。

1 个答案:

答案 0 :(得分:0)

user917879,当您调用e.fillInStackTrace();时,它会重置StackTrace。因此,要打印当前的StackTrace - 在它被重置之前 - 您需要首先调用e.printStackTrace(printOut out)。