1

Why is the output not in the correct order for the following test code:

public static void main(String[] args) {

    boolean test = false;

    try {
        assert test: "will fail with -ea enabled in VM args" ;
    } catch (AssertionError e) {
        e.printStackTrace();
        System.out.println("idk why you would use this but...");
    }

    System.out.println(test + " sneaks in between");

}

run this with "-ea" enabled in the VM arguments (run config)

randomly the output is either:

java.lang.AssertionError: will fail with -ea enabled in VM args
    at Main.main(Main.java:31)
FOO
BAR

(should happen) or:

java.lang.AssertionError: ERROR
FOO
BAR
    at Main.main(Main.java:31)

(should not happen) and sometimes:

java.lang.AssertionError: ERROR
FOO
    at Main.main(Main.java:31)
BAR

I was messing around with "assert" when this happened. I know the code is complete nonsense but it may also happen with other setups. Seconldy consoles are not really used too much in many programs as an official thing, mostly for debugging. But it is still weird.

Is this because the try catch is running on a different thread? or is the stuff happening so fast after eachother that one thing pushes out before the other thing?

I do notice adding a Thread.sleep(1); (which needs to be thrown or caught) does make it always go in chronological order, so...

Why does it not print the code in chronological order?

AgentM
  • 406
  • 4
  • 18

1 Answers1

1

printStackTrace() prints to the error out. How that chronologically lines up with the standard out is indeterminate. You can try calling flush() on System.out, but I can't assure you the result will ever be as you expect unless you specifically print the stack trace to standard out using one of the other available methods.

nitind
  • 19,089
  • 4
  • 34
  • 43
  • Yes, I got a correct result when specifying the PrintStream using e.printStackTrace(System.out); (except the text not being red) – AgentM May 13 '16 at 17:38
  • also I guess: http://stackoverflow.com/questions/6121786/java-synchronizing-standard-out-and-standard-error then also answers it, (edit) note that I didn't know that printStackTrace() was using System.err output stream, I didn't even think about that. – AgentM May 13 '16 at 17:40