Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After closing stdout: Java silently swallows everything written to stdout

Tags:

java

stdout

Have a look at this example:

import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {

  public static void main(String[] args) {
    System.out.println("hi there!");
    System.out.close();
    System.out.println("I'm silently swallowed :(");
    System.out.flush(); // even flushing and closing again
    System.out.close(); // doesn't throw an Exception
    try {
      FileOutputStream fos = new FileOutputStream(FileDescriptor.out);
      fos.flush(); // same goes for this more direct approach
      fos.close();
    } catch (IOException e) {
      e.printStackTrace(System.err);
    }
  }
}

Why doesn't the JVM tell me somehow, that writing to stdout failed? I would expect to get an Exception somewhere.

How else could I detect such a situation?

like image 917
S1lentSt0rm Avatar asked Mar 20 '26 02:03

S1lentSt0rm


1 Answers

Official specification says it all.

Unlike other output streams, a PrintStream never throws an IOException; instead, exceptional situations merely set an internal flag that can be tested via the checkError method.

If your question is "why did they decide to do it this way", then all we can do is make educated guesses, but opinions are off-topic on this site.

like image 158
Marko Topolnik Avatar answered Mar 22 '26 14:03

Marko Topolnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!