简体   繁体   中英

Why is System.err.println is printed before then System.out.println?

I was tryingout Logger example from wiki chain of responsibility article. running the example in idea it prints:

Sending to stderr: An error has occurred.
Writing to stdout: Entering function y.
Writing to stdout: Step1 completed.
Sending via email: Step1 completed.
Writing to stdout: An error has occurred.
Sending via email: An error has occurred.

but when i put a break point in stderrs writeMessage

class StderrLogger extends Logger {
    public StderrLogger(int mask) {
        this.mask = mask;
    }

    protected void writeMessage(String msg) {
        System.err.println("Sending to stderr: " + msg);//break out here
    }
}

it prints all the messags except std err, there is no threads involved here, then why its printing stderr at first line in run case?.

System.err flushes differently from System.out in Eclipse.

Try this in Eclipse:

public class Derp {
    public static void main(String[] args) {
        for(int i = 0; i < 10; i++) {
            System.out.println("OUT");
            System.err.println("ERR");
        }
    }
}

This will randomly print out most of the OUT s and most of the ERR s in big chunks. However, this is an Eclipse issue, not a Java issue, as pointed out by Evgeniy Dorofeev.

If you run this sample program in a terminal, you will notice the correct output, without any flushing needed.

Update: Thanks to Evgeniy Dorofeev for pointing this out! The flushing not working is an Eclipse problem!

System.out.println -> Sends the output to a standard output stream. Generally monitor.

System.err.println -> Sends the output to a standard error stream. Generally monitor.

The streams out and err are independent.

To get the desired output you must flush the streams or just use just one stream for all outputting.

You can use System.out.flush(); and System.err.flush(); in your code

如果您从Eclipse打印它,这是一个已知的错误https://bugs.eclipse.org/bugs/show_bug.cgi?id=32205

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM