Some days ago I realized that PrintWriter (as well as PrintStream) never throw an IOException when writing, flushing or closing.
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()).
My question is: why would one want to have such behavior? Isn't that bad API design?
It's possible that the design was done by someone coming from a C background where stdio errors are handled in a similar fashion. Since I'm used to that paradigm, I wouldn't call it bad, but I'd agree that it is inconsistent.
I also agree with the comment about trying to make PrintWriter easier to use. The IO classes in Java are confusing (at least for everyone I know) and perhaps someone was just trying to make life a little bit easier.
I don't really know the story, but I think it was to make Java easier for newer programmers who the designers wanted to be able to use simple stdio printing methods without the need to know what exceptions are. So in that regard it is good design (I agree with you somewhat though).
I wonder if its because IOExceptions are checked, this would require you placing a try catch block around every System.out. call.
update: Or a throws in your method signature.
That would get annoying very quickly.
I think that since
System.out
andSystem.err
are instances ofPrintStream
, 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 existingPrintStream
.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.Sun / Oracle should have added two write-like functions, one that throws an IOException and another that doesn't throw anything.