Java9引入了StackWalker API作为线程.getStackTrace()或Throwable.getStackTrace()和SecurityManager.getClassContext(). 需要一个额外的机制来遍历延迟帧和堆栈,以便在需要时对堆栈进行有效的访问。
如果我们需要访问异常堆栈跟踪的每个堆栈元素,则可以使用Throwable 类的getStackTrace()方法。它返回一个StackTraceElement数组 。
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)