Java: Why don't the PrintWriter or PrintStream

2019-05-03 08:39发布

问题:

Possible Duplicate:
PrintWriter and PrintStream never throw IOExceptions

Maybe the question is a bit "strange". But i'm curious to know why both PrintWriter and PrintStream don't check automatically runtime exceptions , and they provides a checkError() method.

Thanks to all in advance.

回答1:

For PrintStream which is often writing to std out or err, these stream might have been closed or discarded but you don't want the program to fail unexpectedly as a results.

PrintWriter is in many ways the Writer version of PrintStream, though I am not sure it was a good idea to repeat the mistakes of PrintStream. ;)

The fact PrintWriter doesn't report IOException makes it a poor choice for writing text to a Socket where you often need to know the connection has failed.



回答2:

I think it's primarily because System.err is a PrintStream.

When you're handling exceptions in a catch block, calling e.printStackTrace() is common and it writes to System.err. If that call threw an exception, you would lose the original exception and get the PrintStream error thrown from your code instead. You would then need an extra try/catch inside your catch block to prevent that problem, which makes a big mess.

Note that JDK 1.7 addresses the problem of throwing an exception from a catch block, and allows you to access both exceptions.