简体   繁体   中英

Invorking fillInStackTrace method after invoked printStackTrace method

Blow is a example copied from 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)

My question is why i first invoke e.printStackTrace(printOut out ) method before the fillInStackTrace mehod, and then the fillInStackTrace seems not available. Any one can do me a faver, thanks in advance.

user917879, When you call e.fillInStackTrace(); it resets the StackTrace. So, to print the current StackTrace - before it is get reset - you need to invoke the e.printStackTrace(printOut out ) first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM