Laz*_*don 3 java printstacktrace
在下面的代码片段中,该printStackTrace()方法在catch block.中调用.运行程序后,您可以看到有时printStackTrace()连续几次运行而不是按printStackTrace()- > catch block- > 的顺序运行finally block.
如果您更改static boolean b为false然后按System.out.print(e)顺序执行.
那么为什么printStackTrace()表现方式不同呢?(带线程的东西??)
public class PrintStackTrace {
static boolean b = true;
public static void main(String[] args){
for(int i = 0; i < 100; i++){
try{
throw new Exception("[" + i + "]");
}
catch(Exception e){
if(b){
e.printStackTrace();
}
else{
System.out.print(e);
}
System.out.print(" Catch: " + i);
}
finally{
System.out.print(" Finally: " + i);
}
System.out.println();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Lui*_*oza 12
这是因为printStackTrace写入System.err时System.out.println写入System.out.即使两个System.err和System.out用于输出消息的相同底层资源(例如相同的文件或同一控制台),它们冲洗在不同的时刻.
如果要获得同步输出,请同时编写例外System.out:
e.printStackTrace(System.out);
Run Code Online (Sandbox Code Playgroud)
或者甚至更好,使用记录器,它已经将输出同步到共享资源,并为您提供有关消息中输出内容的更多选项,例如类,方法,日期和时间,线程名称等,以及编写日志消息等其他好处在数据库而不是文本文件,然后.