1

I'm developing a main class that writes potential exceptions by means of e.printStackTrace() and which finishes with

System.err.flush();
System.out.println("\n>>> EXITING...");

The issue is that when exception trace is big, my exiting message is still printed in the middle of all the error sermon.

What I am doing wrong?

Whimusical
  • 6,401
  • 11
  • 62
  • 105
  • 4
    Please post a [MCVE](http://stackoverflow.com/help/mcve). – Elliott Frisch Apr 14 '16 at 17:08
  • Are multiple threads involved? – AJNeufeld Apr 14 '16 at 17:24
  • I'm fear it's not deterministic, since my private code uses different operations with different lags, and the buffer can be full or not, and every terminal has its performance. It's a bit of a hit and miss until I reach the situation, so I don't think a benchmarking is needed. It must be a conceptual problem. C'mon its single-threaded, and logically replicable with 3 lines. – Whimusical Apr 14 '16 at 17:24
  • At least somebody could tell if it's an expected issue or not, before furthering research – Whimusical Apr 14 '16 at 17:25
  • 3
    `err` and `out` are two separate streams. Even if you flush the output, that just means all the characters have been sent to the o/s. The terminal(?) reading both streams might still interleave the two streams when it displays them. – AJNeufeld Apr 14 '16 at 17:29
  • I was fearing that. Thanks! Could you write it in an answer form so I can accept it? – Whimusical Apr 14 '16 at 17:30

2 Answers2

2

The System.err and System.out are two separate streams. Even if you flush the output, that just means all the characters have been sent to the o/s. The terminal(?) reading both streams might still interleave the two streams when it displays them.

One remedy might be to tie the streams together, effectively directing the System.err stream to be written to System.out, but you will lose any colouring etc that distinguishes the two streams when displayed.

AJNeufeld
  • 8,526
  • 1
  • 25
  • 44
  • 1
    I used this solution with the addition of a small ninja trick to overcome the problem of loss of color. In the case of error messages I added the character \uD83D\uDD25 at the string to highlight the errors! :). Examle: System.out.println("\uD83D\uDD25\uD83D\uDD25\uD83D\uDD25 -> My error!!!"); – Andrea Zonzin Sep 07 '19 at 20:09
0

Had the same problem. I added Thread.sleep(5) after the flush. Then it worked.

  • 1
    try to highlight the keywords and be clear with the format it will help to reach out your answer for others – Agilanbu Dec 15 '18 at 09:01