Search code examples
exceptionjava.util.scannerprintstacktrace

Strange behavior with 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");

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)

and sometimes this:

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

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?


Solution

  • printStackTrace, as per the documentation, prints to the standard error stream:

    public void printStackTrace() – Prints this throwable and its backtrace to the standard error stream.

    ...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.

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