本文介绍了printStackTrace()的异常行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

printStackTrace()的行为就像在等待输入后在自己的线程中运行。这是我的代码:

printStackTrace() acts as if it runs in its own thread after waiting for input. Here's my code:

try {
    new Scanner(System.in).nextLine();
    throw new Exception();
} catch (Exception e) {
    e.printStackTrace();
}
System.out.print("STUFF");

我有时会得到预期的输出(使用 STUFF 结尾),但有时我会得到:

I sometimes get the expected output (with STUFF at the end), but sometimes I get this:

blabla // the scanner input
java.lang.ExceptionSTUFF
    at Test.main(Test.java:7)

有时是这样的: / p>

and sometimes this:

blabla
java.lang.Exception
STUFF   at Test.main(Test.java:7)

System.in.read()产生相同的结果。完全删除该行可产生预期的结果。在实际的程序中,我注意到了这个问题,堆栈跟踪的时间更长,并且 STUFF 的输出总是出现在预期的位置或在上面的第二个输出中-在开始时

Replacing the scanner with System.in.read() yields the same results. Removing the line entirely yields the expected result. In the actual program where I noticed this problem, the stack trace was much longer, and the STUFF output always appeared either as expected or as in the second output above - at the beginning of the second line.

是什么原因造成的,我该如何解决?

What's causing this, and how can I solve it?

推荐答案

printStackTrace ,根据文档:

... System.err 。然后,您正在写入 System.out 。这两个是不同的流,因此在不同的时间刷新到实际输出。照原样保留代码,等效于中概述的问题。

...which is System.err. Then you are writing to System.out. Those two are different streams and therefore get flushed to the actual output at different times. Leaving the code as it is, it is equivalent to the problem outlined in this question.

要解决此问题,您可以手动刷新输出流或将异常打印到 System.out 而不是 System .err 。您可以使用的printStackTrace变量: e.printStackTrace(System.out);

To fix the issue, you could either manually flush your output streams or print your exception to System.out instead of System.err. You could use the variant of printStackTrace that accepts a PrintStream with standard output as a parameter: e.printStackTrace(System.out);

这篇关于printStackTrace()的异常行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 17:26