views:

582

answers:

4

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?

+1  A: 

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).

Josh
A: 

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.

jdigital
+1  A: 

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.

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.

erickson
+2  A: 

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.

Owen
A checked exception doesn't strictly require a try-catch block, of course. PrintStream is rarely used in production code, and its usage within the core libraries is limited to logging, where failures can be safely ignored.
erickson