2011-11-29 60 views
0

吹塑是想在Java中4版复制一个例子Invorking fillInStackTrace方法调用后的printStackTrace方法

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的了)方法,然后fillInStackTrace似乎不可用。任何人都可以为我提供帮助,请提前致谢。

回答

0

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

+0

感谢您的评论,但我的意思是,如果我在e.fillInStackTrace()之前调用e.printStackTrace(),则原因行不是从“throw(Exception)e.fillInStackTrace()”行开始,而是从原始的“抛出新的异常(”从f()“)”行抛出。所以我不知道为什么会发生? – user917879

+0

是的,因为在h()中调用f()并引发第一个异常(“从f()”抛出)。 它被h()中的catch捕获,并且第一个StackTrace被打印。 然后,StackTrace被重置并抛出异常。 它被main()中的catch捕获并在那里打印第二个StackTrace。 这里调用“throw(Exception)e.fillInStackTrace();”堆栈被重置。但发生的异常不会改变。因此,尽管堆栈的顶点改为Rethrowing.java:15(在SOF.Rethrowing.h(Rethrowing.java:15)),抛出的异常“从f()抛出”是原样传递的。 – namalfernandolk

+0

亿万谢谢,但我仍然不明白什么是“StackTrace被重置”的意思,是否意味着当我打电话给e.printStackTrace()时,它已经做了重置操作“填充StakTrace”,所以它不会提供当调用e.fillInStackTrace()时。那就对了? – user917879