每当我们尝试使用 printStackTrace()
方法打印堆栈跟踪时,为什么输出不按预期顺序?假设我们有一些打印语句以及 printStackTrace()
并且输出不按预期顺序。
public class Main {
public static void main(String[] args) {
Main m = new Main();
m.test1();
System.out.println("main method");
}
public void test1() {
System.out.println(test2());
System.out.println("test1");
}
public int test2() {
try {
throw new Exception();
} catch (Exception e) {
System.out.println("exception");
e.printStackTrace();
} finally {
}
return 2;
}
}
预期输出应该是:
exception
java.lang.Exception
at com.infor.jdbc.Main.test2(Main.java:18)
at com.infor.jdbc.Main.test1(Main.java:12)
at com.infor.jdbc.Main.main(Main.java:7)
2
test1
main method
但实际结果是:
exception
java.lang.Exception //from printStackTrace
2
test1
main method
at com.infor.jdbc.Main.test2(Main.java:18) //from printStackTrace
at com.infor.jdbc.Main.test1(Main.java:12)
at com.infor.jdbc.Main.main(Main.java:7)
最佳答案
缓冲输出流被写入两个单独的输出而不刷新(“stderr”和“stdout”)。打印您的消息,打印堆栈跟踪,然后刷新,您将看到您期望的行为。
public int test2() {
try {
throw new Exception();
} catch (Exception e) {
System.err.println("exception");
e.printStackTrace(System.err);
System.err.flush();
} finally {
}
return 2;
}
关于java - 为什么异常方法的 printstacktrace() 在调用时不会打印到控制台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57720509/