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

喜欢而已 提交于 2019-12-05 08:51:42

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.

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.

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