Access Each Stack Element of StackWalker in Java 9



In this article, we will learn to access each stack element of StackWalker in Java 9. We will learn about the StackWalker API and its methods, and use of getStackTrace() method for accessing each stack element.

StackWalker API

StackWalker API allows easy filtering and lazy access to execute tasks within any method. It is an efficient API for obtaining stack trace information in Java 9. StackWalker API is 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.

The following are some of the common methods of the StackWalker API:

  • getCallerClass?(): This method gets the Class object of the caller who invoked the method.
  • getInstance?(): This method returns a StackWalker instance.
  • walk?(): This method applies the given function to the stream of StackFrames for the current thread.

Accessing Each Stack Element

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

First, we will define 3 classes: Test1, Test2, and StackWalkerTest, and the StackWalkerTest class contains the main() method. Then the main() creates a Test1 object and calls its test() method.

After that Test1.test() method creates a Test2 object and calls its test() method, and it performs division by zero, which throws an ArithmeticException error.

The caught exception stack trace is accessed via e.getStackTrace(), then the stack trace is converted to an array of stream. At last, each stack trace element is printed using the forEach() method.

Example to Access Each Stack Element of StackWalker

Below is an example to access each stack element of StackWalker in Java 9:

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)
Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-06-16T16:35:18+05:30

227 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements