本文介绍了为什么printStackTrace()和其他方法之间的执行顺序似乎是不确定的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的下面的代码段中, catch块中调用了 printStackTrace()方法。运行程序后,您可以看到有时 printStackTrace()连续多次运行,而不是按 printStackTrace()的顺序运行 - > catch block - > finally block

In my code snippet below, the printStackTrace() method is called in the catch block. After running the program you can see that sometimes the printStackTrace() runs several times in a row instead of running in the order of printStackTrace() --> catch block --> finally block.

如果将静态布尔值b 更改为 false ,则 System.out.print(e)按顺序执行。

If you change the static boolean b to false then the System.out.print(e) executes in order.

那么为什么 printStackTrace()表现得与众不同? (带线程的东西??)

So why does the printStackTrace() behaves in different way? (something with the threads??)

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();
        }
    }
}


推荐答案

这是因为 printStackTrace 写入 System.err System.out。 println 写入 System.out 。即使 System.err System.out 都使用相同的底层资源来输出消息(例如同一个文件)或者相同的控制台),它们在不同的时刻刷新。

It is because printStackTrace writes in System.err while System.out.println writes on System.out. Even if both System.err and System.out use the same underlying resource for the output messages (e.g. the same file or the same console), they flush at different moments.

如果你想要一个同步输出,写下<$ c中的例外$ c> System.out 以及:

If you want to have a synchronized output, write the exceptions in System.out as well:

e.printStackTrace(System.out);

或者甚至更好,使用记录器,它已经将输出同步到共享资源并为您提供更多信息关于消息中输出内容的选项,例如类,方法,日期和时间,线程名称等,以及在数据库而不是文本文件中写日志消息等其他好处,以及。

Or even better, use a logger, which already synchronizes the outputs into a shared resource and give you more options about what's being output in the message e.g. Class, method, date and time, thread name, etc. among other benefits like writing log messages in database instead of a text file, and on.

这篇关于为什么printStackTrace()和其他方法之间的执行顺序似乎是不确定的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 17:26