如何从close()正确处理IOException [英] How to properly handle an IOException from close()

查看:418
本文介绍了如何从close()正确处理IOException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java I / O类 java.io.Reader java.io.Writer java.io.InputStream java.io.OutpuStream 及其各种子类都有一个 close() 方法可以抛出 IOException



是否有正确的方式达成共识处理这样的例外?



我经常看到建议,只是默默地忽略他们,但是觉得错了,至少在资源开放写作的情况下,一个问题关闭文件可能意味着未刷新的数据无法写入/发送。



另一方面,在阅读资源时,我完全不清楚为什么 close()可能会抛出,该怎么做。



那么有什么标准的建议吗?



相关问题是关闭是否抛出IOException? / a>,但这更多关于w

记录它。 / p>

你不能真正地做任何事情(例如写一些从错误中恢复的代码),但它通常值得让某人知道关于它。



编辑:

经过进一步的调查和阅读其他评论,我会说如果你想处理它,那么你将不得不知道实施细节。相反,你可能需要知道实现的细节,以决定是否需要处理它。



实际上,我不能想到任何流的例子或写入可以正常工作,而不会抛出异常,但关闭会。


The Java I/O classes java.io.Reader, java.io.Writer, java.io.InputStream, java.io.OutpuStream and their various subclasses all have a close() method that can throw an IOException.

Is there any consensus on the proper way to handle such exceptions?

I have often seen recommendations to just silently ignore them, but that feels wrong, and at least in case of resources opened for writing, a problem while closing the file might mean that unflushed data could not be written/sent.

On the other hand, when reading resources, I'm totally unclear on why close() might throw and what to do about it.

So is there any standard recommendation?

A related question is Does close ever throw an IOException?, but that is more about which implementations really do throw, not about how to handle the exceptions.

解决方案

Log it.

You can't really do anything about it (for example write some code that recovers from the error), but its generally worth letting somebody know about it.

Edit:
After further investigation and reading the other comments, I'd say that if you do want to handle it then you're going to have to know details of the implementation. Conversely you probably need to know details of the implementation to decide whether you need to handle it.

Realistically though, I can't think of any examples of streams where the reading or writing would work correctly without throwing an exception, but the closing would.

这篇关于如何从close()正确处理IOException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆