文件关闭时,为什么我会关心IOExceptions? [英] Why would I care about IOExceptions when a file is closed?

查看:84
本文介绍了文件关闭时,为什么我会关心IOExceptions?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常在Java代码中看到这种事情......

I've see this sort of thing in Java code quite often...

try
{
    fileStream.close();
}
catch (IOException ioe)
{
    /* Ignore. We do not care. */
}

这是合理的还是骑士的?

Is this reasonable, or cavalier?

我什么时候关心关闭文件失败?忽略此异常有什么影响?

When would I care that closing a file failed? What are the implications of ignoring this exception?

推荐答案

至少记录异常。

如果由于无法刷新数据而导致关闭文件的尝试失败,我偶尔会看到它发生。如果您只是吞下了异常,那么您在没有意识到的情况下丢失了数据。

I've seen it happen occasionally, if the attempt to close the file fails due to it not being able to flush the data. If you just swallow the exception, then you've lost data without realizing it.

理想情况下,如果您已经处于另一个异常情况中,您应该吞下该异常异常(即你在finally块中,但是由于另一个异常,而不是完成了try块)但是如果你的操作是成功的话就抛出它。不幸的是,这有点难看:(

Ideally, you should probably swallow the exception if you're already in the context of another exception (i.e. you're in a finally block, but due to another exception rather than having completed the try block) but throw it if your operation is otherwise successful. Unfortunately that's somewhat ugly to sort out :(

但是,你应该至少登录它。

But yes, you should at least log it.

这篇关于文件关闭时,为什么我会关心IOExceptions?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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