Java 调用printStackTrace方法后调用fillInStackTrace方法

Java 调用printStackTrace方法后调用fillInStackTrace方法,java,exception,Java,Exception,Blow是从Think in Java 4 edition复制的一个示例 public class Rethrowing { public static void f() throws Exception { System.out.println("originating the exception in f()"); throw new Exception("thrown from f()"); }

Blow是从Think in Java 4 edition复制的一个示例

   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)

我的问题是,为什么我先调用e.printStackTraceprintOut方法,然后调用fillInStackTrace方法,而fillInStackTrace似乎不可用。任何人都可以帮我一个忙,提前谢谢

user917879,当您调用e.fillInStackTrace时;它重置堆栈跟踪。因此,要打印当前StackTrace,在重置之前,您需要首先调用e.printStackTraceprintOut。

谢谢您的评论,但我的意思是,如果我在e.fillInStackTrace之前调用e.printStackTrace,则原因行不会在抛出ExceptionOne.fillInStackTrace行开始,但从最初开始,从f线抛出新的例外。所以我不知道为什么会发生这种情况?是的,因为f中的第一个异常rown是在h中调用f并抛出时发生的。它被h中的捕获物捕获,并打印第一个StackTrace。然后,StackTrace被重置并抛出异常。它被catch in main捕获,并在那里打印第二个StackTrace。在这里调用抛出异常e.fillInStackTrace时;堆栈被重置。但是发生的异常没有改变。因此,尽管堆栈的顶点在SOF.Rethrowing.hrestrowing.java:15处更改为Rethrowing.java:15,但从f抛出的抛出异常仍按原样传递。十亿,谢谢,但我仍然不明白StackTrace是什么意思,即get reset的意思,你的意思是当我调用e.printStackTrace时,它已经重置了操作fill StakTrace,因此,下次调用e.fillInStackTrace时它将不可用。是吗?正如您所知,在调用堆栈中,调用的最后一个方法位于堆栈顶部,调用的第一个方法位于底部。然后,如果某个方法中发生异常,它将从调用堆栈的顶部传播到底部,直到在某个点被捕获为止。因此,当您捕获异常并调用e.printStackTrace时,它将显示从异常发生时调用堆栈的外观。因此,当您调用fillInStackTrace时,它将改变这一点,即e.fillInStackTrace所在的行发生异常;打电话。这就是StackTrace重置的含义。