如何从close()正确处理IOException

编程入门 行业动态 更新时间:2024-10-18 10:13:52
本文介绍了如何从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

本文发布于:2023-11-24 04:40:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1624007.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确处理   close   IOException

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!