Search code examples
javajava-9

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);
        }
    }
}

Solution

  • 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.