Home> Java> javaTutorial> body text

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

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

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

Java 9 introducedStackWalkerAPIasThread.getStackTrace()orThrowable Alternatives to .getStackTrace()andSecurityManager.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 thegetStackTrace()method of theThrowableclass. It returns anarrayof StackTraceElements.

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

Output

Test2.test(StackWalkerTest.java:14) Test1.test(StackWalkerTest.java:7) StackWalkerTest.main(StackWalkerTest.java:23)
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!