Why does the execution order between the printStackTrace() and the other methods appear to be nondeterministic?

后端 未结 1 1122
有刺的猬
有刺的猬 2020-12-06 14:51

In my code snippet below, the printStackTrace() method is called in the catch block. After running the program you can see that sometimes the

相关标签:
1条回答
  • 2020-12-06 15:29

    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.

    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.

    0 讨论(0)
提交回复
热议问题