防范异常(预防性维护)与网络/文件系统调用时? [英] Guarding against exceptions (preventative maintenance) when working with network / file system calls?

查看:99
本文介绍了防范异常(预防性维护)与网络/文件系统调用时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个朋友是谁在不同意我的这一点,我只是希望得到一些反馈,谁是正确的和错误在这种情况下。

I have a friend who is in disagreement with me on this, and I'm just looking to get some feedback as to who is right and wrong in this situation.

FileInfo file = ...;

if (file.Exists)
{
    //File somehow gets deleted

    //Attempt to do stuff with file...
}

我的朋友指出的问题是,所以,如果存在什么文件,当我检查是否存在?有什么防范的检查后右侧的文件被删除,并试图访问它导致异常的机会。那么,它甚至值得的前手来检查是否存在?

The problem my friend points out is that, "so what if the file exists when I check for existence? There is nothing to guard against the chance that right after the check the file gets deleted and attempts to access it result in an exception. So, is it even worth it to check for existence before-hand?"

我能想出的唯一的事情就是MSDN显然不会在他们的榜样支票,所以必须有更多的东西。 MSDN - FileInfo的。但是,它也有我不知道...是额外调用甚至值得吗?

The only thing I could come up with is that MSDN clearly does a check in their examples, so there must be more to it. MSDN - FileInfo. But, it does have me wondering... is the extra call even worth it?

推荐答案

我想兼得如果(file.Exists)尝试捕捉。只有在异常处理依托并没有明确表达你的想法。 如果(file.Exists)是自我解释。

I would have both if (file.Exists) and a try catch. Relying only on exception handling does not express explicitly what you have in mind. if (file.Exists) is self-explaining.

如果有人删除文件只是检查之间的毫秒并与文件工作,你仍然可以得到一个异常。尽管如此,也有其他的条件下,这可能导致一个异常:文件是只读;你没有请求的安全权限,等等。

If someone deletes the file just in that millisecond between checking and working with the file, you can still get an exception. Nevertheless, there are also other conditions, which can lead to an exception: The file is read-only; you do not have the requested security permissions, and more.

这篇关于防范异常(预防性维护)与网络/文件系统调用时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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