简体   繁体   中英

Stackwalker within try-catch block java 9

I am trying to print stack walker in exception block but it is displaying only current class

public class Test1 {
    public void test() throws Exception{
        Test2 test2 = new Test2();
        test2.test();
    }
}
public class Test2 {
    public void test() throws Exception{
        System.out.println(1/0);
    }
}
public class TestStackWalker {
      public static void main(String[] args) {
        Test1 test1 = new Test1();
        try {
            test1.test();
        } catch (Exception e) {
           StackWalker stack = StackWalker.getInstance();
           stack.forEach(System.out::println);
        }
    }
}

From StackWalker docs:

The walk method opens a sequential stream of StackFrames for the current thread and then applies the given function to walk the StackFrame stream.

Since you are calling it from your main method - there is only one StackFrame allocated and is being printed:

TestStackWalker.main(TestStackWalker.java:10)

If you want have access to each stack element of you exception's stack trace - use Throwable::getStackTrace which returns array of StackTraceElement :

class TestStackWalker {
    public static void main(String[] args) {
        Test1 test1 = new Test1();
        try {
            test1.test();
        } catch (Exception e) {
            Arrays.stream(e.getStackTrace()).forEach(System.out::println);
        }
    }
}

which will print:

Test2.test(Test2.java:3)
Test1.test(Test1.java:4)
TestStackWalker.main(TestStackWalker.java:7)

If you want only to print it Throwable::printStackTrace should be enough.

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