关闭 stdout 后:Java 静静地吞下所有写入 stdout 的内容
After closing stdout: Java silently swallows everything written to stdout
看看这个例子:
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);
}
}
}
为什么 JVM 不以某种方式告诉我写入标准输出失败?我希望在某处得到一个异常。
我还能如何检测到这种情况?
Official specification 说明了一切。
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.
如果您的问题是 "why did they decide to do it this way",那么我们所能做的就是做出有根据的猜测,但本网站上的观点是离题的。
看看这个例子:
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);
}
}
}
为什么 JVM 不以某种方式告诉我写入标准输出失败?我希望在某处得到一个异常。
我还能如何检测到这种情况?
Official specification 说明了一切。
Unlike other output streams, a
PrintStream
never throws anIOException
; instead, exceptional situations merely set an internal flag that can be tested via thecheckError
method.
如果您的问题是 "why did they decide to do it this way",那么我们所能做的就是做出有根据的猜测,但本网站上的观点是离题的。