Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of System.err?

Tags:

In UNIX, I'm supposed to write a Java file that will print "EXIT 1" to the standard error, and then exit with a status of 1.

Here is my approach..

System.err.println("EXIT 1"); System.exit(1); 

Is this what I'm supposed to do?

If so, how am I supposed to use it in the Unix shells? When I compile and run it in the bash, it just prints "EXIT 1" (so it does the same thing as System.out.println, why should I use "err"?). What is the "standard error" here?

like image 307
Gavin Z. Avatar asked Jan 17 '14 23:01

Gavin Z.


1 Answers

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.

like image 98
MultiplyByZer0 Avatar answered Oct 05 '22 23:10

MultiplyByZer0