What is the point of System.err?
Every running program has these three streams:
- Standard input (stdin), which normally comes from the keyboard. Exposed as
System.in
- Standard out (stdout), which normally goes to the console. Exposed as
System.out
- Standard error (stderr), which normally also goes to the console. Exposed as
System.err
Your program is correct – it does print to stderr. But under normal circumstances, the stderr stream goes to the console just like the stdout stream, so they are visually indistinguishable.
However, the reason you should use stderr instead of stdout for error messages, is redirection. That means that you send stderr to a file instead of the console. Meanwhile, stdout will be unaffected, because the two streams are independent.
For example, you can do this in bash, cmd, PowerShell, etc:
$ java Program 2> errors.txt
Now, all output with System.err.println()
will end up in errors.txt
, while System.out.println()
will still go to the screen. This can help with debugging.
There are three data streams associated with nearly every process:
- Standard Input: This is the stream of input into a program, either from a terminal, a console, piped output from another process, or some other means.
- Standard Error: This is where all debugging and error messages should go. This is so that this sort of information can easily be separately captured from the regular output of a program. Web servers do this, by sending error messages to an
error_log
file viastderr
, while the normal log file would be e. g.access_log
. - Standard Output: This is the where all typical, expected output that a user running a program should expect to see said output appear.
Standard Output (stdout
) and Standard Error (stderr
) are nearly always the first and second output streams coming from a process, respectively. This allows me to do something like /path/to/my/neat/program > logs/program.log 2> logs/program.err
and have output and errors nicely sorted.