xhtml
 

Error Messages

The variable System.out represents an output stream of text that is usually sent to the screen. That's why we have been using System.out.println to display results.

For error messages, it is better to use System.err. This is another output stream of text, which is also usually sent to the screen. So, it seems that using System.err.println for error messages usually looks exactly the same as using System.out.println, so why not just do that?

The answer is to cooperate with command window features. One of the features which most platforms have is output redirection. This means running a program but capturing its output in a file instead of printing it on the screen. For example, you might type a command line like this:

java Check x y z > output.txt

The last part of the line > output.txt is not sent to the program, but instead the > character is interpreted as an instruction to redirect the output to the file called output.txt.

In Java, this only affects the output stream System.out and not the stream System.err. The result is that if something goes wrong, the error message is still displayed to the user and not put into the file. This is usually exactly what you want, so it is polite to use System.err for any error or warning message which you don't regard as part of the normal output of the program.


Back