每当我们尝试使用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;
}
Run Code Online (Sandbox Code Playgroud)
}
预期输出应该是:
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
Run Code Online (Sandbox Code Playgroud)
但实际结果是:
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)
Run Code Online (Sandbox Code Playgroud)
缓冲输出流被写入两个单独的输出而不刷新(“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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3104 次 |
| 最近记录: |