try-catch 块中的 Stackwalker java 9
Stackwalker within try-catch block java 9
我正在尝试在异常块中打印 stack walker 但它只显示当前 class
public class Test1 {
public void test() throws Exception{
Test2 test2 = new Test2();
test2.test();
}
}
public class Test2 {
public void test() throws Exception{
System.out.println(1/0);
}
}
public class TestStackWalker {
public static void main(String[] args) {
Test1 test1 = new Test1();
try {
test1.test();
} catch (Exception e) {
StackWalker stack = StackWalker.getInstance();
stack.forEach(System.out::println);
}
}
}
来自 StackWalker
文档:
The walk method opens a sequential stream of StackFrames
for the current thread and then applies the given function to walk the StackFrame
stream.
因为您是从您的主要方法调用它 - 只有一个 StackFrame
已分配并正在打印 :
TestStackWalker.main(TestStackWalker.java:10)
如果您想访问异常堆栈跟踪的每个堆栈元素 - 使用 Throwable::getStackTrace
which returns array of StackTraceElement
:
class TestStackWalker {
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(Test2.java:3)
Test1.test(Test1.java:4)
TestStackWalker.main(TestStackWalker.java:7)
如果你只想打印它 Throwable::printStackTrace
应该足够了。
我正在尝试在异常块中打印 stack walker 但它只显示当前 class
public class Test1 {
public void test() throws Exception{
Test2 test2 = new Test2();
test2.test();
}
}
public class Test2 {
public void test() throws Exception{
System.out.println(1/0);
}
}
public class TestStackWalker {
public static void main(String[] args) {
Test1 test1 = new Test1();
try {
test1.test();
} catch (Exception e) {
StackWalker stack = StackWalker.getInstance();
stack.forEach(System.out::println);
}
}
}
来自 StackWalker
文档:
The walk method opens a sequential stream of
StackFrames
for the current thread and then applies the given function to walk theStackFrame
stream.
因为您是从您的主要方法调用它 - 只有一个 StackFrame
已分配并正在打印 :
TestStackWalker.main(TestStackWalker.java:10)
如果您想访问异常堆栈跟踪的每个堆栈元素 - 使用 Throwable::getStackTrace
which returns array of StackTraceElement
:
class TestStackWalker {
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(Test2.java:3)
Test1.test(Test1.java:4)
TestStackWalker.main(TestStackWalker.java:7)
如果你只想打印它 Throwable::printStackTrace
应该足够了。