【发布时间】:2016-10-27 11:44:55
【问题描述】:
看看这个例子:
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 不以某种方式告诉我,写入标准输出失败了?我希望得到一个异常somewhere。
我还能如何检测到这种情况?
【问题讨论】:
-
您可以通过
checkError()查看。有一个布尔trouble修饰符以防异常(尝试在所有接缝处捕获是个坏主意;))。这可以通过clearError()重置 -
@DimaSan,我不认为这是重复的,有人问我们为什么要关闭流异常系统的流,这里的问题是为什么当我们使用关闭的流时没有任何不好的事情发生