Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

java - PrintWriter and PrintStream never throw IOExceptions

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...