PrintWriter和PrintStream不会抛出IOExceptions [英] PrintWriter and PrintStream never throw IOExceptions
问题描述
几天前,我意识到 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
的实例,提供了一些更放松的错误处理。正如其他海报所提到的那样,为了顺利地从C / C ++大约1995年过渡。当添加了Reader / Writer API时, PrintWriter
被创建为平行现有的 PrintStream
。
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!