问题描述
几天前我意识到PrintWriter(以及PrintStream)永远不要在写入、刷新或关闭时抛出 IOException.
Some days ago I realized that PrintWriter (as well as PrintStream) never throw an IOException when writing, flushing or closing.
相反,它会在发生错误时设置一个内部标志 (trouble=true
).
不可能得到确切的异常,但只有如果有一些异常(checkError()).
Instead it sets an internal flag (trouble=true
) when an error occurs.
It's not possible to get the exact exception, but only if there was some exception (checkError()).
我的问题是:为什么会有这样的行为?这不是糟糕的 API 设计吗?
My question is: why would one want to have such behavior? Isn't that bad API design?
推荐答案
我认为因为 System.out
和 System.err
是 PrintStream,提供了一些更轻松的错误处理.正如其他海报所提到的,这可能是为了为大约 1995 年从 C/C++ 过渡的人铺平道路.当添加阅读器/编写器 API 时,创建了
PrintWriter
以与现有的 并行打印流
.
I think that since System.out
and System.err
are instances of PrintStream
, some more relaxed error handling was provided. This was probably, as other posters have mentioned, to smooth the way for those transitioning from C/C++ circa 1995. When the Reader/Writer API was added, PrintWriter
was created to parallel the existing PrintStream
.
这种行为非常需要的一个应用程序是日志记录.日志记录是大型应用程序的辅助工具.通常,如果日志记录失败,人们不希望整个应用程序失败.因此,System.err
至少可以忽略异常.
One application where this behavior is extremely desirable is logging. Logging is ancillary to a larger application. Typically, if logging fails, one doesn't want that the entire application to fail. Thus, it makes sense for System.err
, at least, to ignore exceptions.
这篇关于PrintWriter 和 PrintStream 从不抛出 IOExceptions的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!