Java: Why don't the PrintWriter or PrintStream classes throw exception? [duplicate]

此生再无相见时 提交于 2019-12-07 06:47:41

问题


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.



来源:https://stackoverflow.com/questions/12431757/java-why-dont-the-printwriter-or-printstream-classes-throw-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!