How to access each stack element of StackWalker in Java 9?

JavaObject Oriented ProgrammingProgramming

Java 9 introduced StackWalker API as an alternative to Thread.getStackTrace() or Throwable.getStackTrace() and SecurityManager.getClassContext(). This API targets a mechanism to traverse and materialize required stack frames allowing efficient lazy access to additional stack frames when required.

If we need to access each stack element of an exception stack trace, then we can use the getStackTrace() method of Throwable class. It returns an array of StackTraceElement.

Example

import java.util.*;

// Test1 class
class Test1 {
   public void test() throws Exception {
      Test2 test2 = new Test2();
      test2.test();
   }
}

// Test2 class
class Test2 {
   public void test() throws Exception {
      System.out.println(1/0);
   }
}

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

Output

Test2.test(StackWalkerTest.java:14)
Test1.test(StackWalkerTest.java:7)
StackWalkerTest.main(StackWalkerTest.java:23)
raja
Published on 05-Mar-2020 13:37:55
Advertisements