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

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

王林
王林forward
2023-09-05 11:13:021266browse

如何在Java 9中访问StackWalker的每个堆栈元素?

Java 9 introduced StackWalker API as Thread.getStackTrace() or Throwable Alternatives to .getStackTrace() and SecurityManager.getClassContext() . The goal of this API is a mechanism to traverse and materialize the required stack frames, allowing efficient deferred access to additional stack frames when needed.

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

Example

import java.util.*;

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

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

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

Output

<strong>Test2.test(StackWalkerTest.java:14)
Test1.test(StackWalkerTest.java:7)
StackWalkerTest.main(StackWalkerTest.java:23)</strong>

The above is the detailed content of How to access each stack element of StackWalker in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete