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

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

王林
Release: 2023-09-05 11:13:02
forward
1302 people have browsed it

如何在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);
      }
   }
}
Copy after login

Output

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

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template