代码之家  ›  专栏  ›  技术社区  ›  S1lentSt0rm

关闭stdout后:Java会默默地吞下所有写入stdout的内容

  •  3
  • S1lentSt0rm  · 技术社区  · 9 年前

    看看这个例子:

    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不告诉我写stdout失败了?我希望得到一个例外 在某处 .

    否则我怎么能发现这种情况?

    1 回复  |  直到 9 年前
        1
  •  4
  •   Marko Topolnik    9 年前

    Official specification 都说了。

    与其他输出流不同 PrintStream 从不扔 IOException ; 相反,异常情况仅设置一个内部标志,可以通过 checkError 方法

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

    推荐文章