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.
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); } } }
Test2.test(StackWalkerTest.java:14) Test1.test(StackWalkerTest.java:7) StackWalkerTest.main(StackWalkerTest.java:23)
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!