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?
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()).
OutputStreams are meant for binary data. Writers (including PrintWriter ) are meant for text data. You may not see the difference in your specific situation as you're calling PrintWriter.
PrintWriter class is the implementation of Writer class. By using PrintWriter than using System. out. println is preferred when we have to print a lot of items as PrintWriter is faster than the other to print data to the console.
Class PrintWriter. Prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream . It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
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.
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 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With