【问题标题】:After closing stdout: Java silently swallows everything written to stdout关闭标准输出后:Java 默默吞下所有写入标准输出的内容
【发布时间】: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,我不认为这是重复的,有人问我们为什么要关闭流异常系统的流,这里的问题是为什么当我们使用关闭的流时没有任何不好的事情发生

标签: java stdout


【解决方案1】:

Official specification 说明一切。

与其他输出流不同,PrintStream 永远不会抛出 IOException;相反,异常情况只是设置一个内部标志,可以通过checkError 方法进行测试。

如果您的问题是“他们为什么决定这样做”,那么我们所能做的就是做出有根据的猜测,但意见在本网站上是题外话。

【讨论】:

  • “他们为什么决定这样做”这不是我的问题,但现在是 :) 我觉得这很奇怪......但感谢您的回答!
  • 想象一下,必须将每个 println 语句放在一个 try-catch 中。您可能会争辩说,他们本可以为此发明另一个未经检查的 IOException,但在 Java 1.0 时代,这并没有引起人们的注意。
猜你喜欢
  • 2013-11-06
  • 2018-08-29
  • 1970-01-01
  • 2012-06-08
  • 2013-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多