如果我的方法抛出自己的异常,或是让.NET抛出,如果文件不存在? [英] Should my method throw its own exception, or let .NET throw if a file doesn't exist?

查看:154
本文介绍了如果我的方法抛出自己的异常,或是让.NET抛出,如果文件不存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的代码:

public void ReadSomeFile(string filePath)
{
    if (!File.Exists(filePath))
        throw new FileNotFoundException();

    var stream = new FileStream(filePath, ....)
    .....
}

我应该抛出一个异常,我自己(请参阅 File.Exists 检查)? 的FileStream 就已经抛出 FileNotFoundException异常如果该文件不存在。什么是良好的编程习惯吗?代码分析说,我们要验证我们的参数。但是,如果我直接传递的参数,以另一种方法(我或别人的代码),该方法会抛出异常本身,又是什么在我的代码验证参数的优势在哪里?

Should I throw an exception myself (see the File.Exists check)? FileStream will already throw FileNotFoundException if the the file doesn't exist. What is good programming practice here? Code analysis says that we should validate our parameters. But if I am passing that parameter directly to another method (mine or someone else code) and that method will throw exception itself, then what is advantage of validating argument in my code?

推荐答案

如果(File.Exists(F)){DoSomething的(F)} (或其否定)为抗模式。该文件可以删除或在这两个语句之间创建的,所以它没有什么意义,以检查其是否存在这样的。

if (File.Exists(f)) { DoSomething(f) } (or the negation thereof) is an anti-pattern. The file can be deleted or created in between those two statements, so it makes little sense to check its existence like that.

除此之外,由于在评论中指出,而 File.Exists()可能返回true,该文件的实际开盘则仍可失败的原因有多种。所以你必须重复错误检查和周围的文件开幕投掷。

Apart from that, as pointed out in the comments, while File.Exists() may return true, the actual opening of the file can then still fail for a variety of reasons. So you'll have to repeat the error checking and throwing around the opening of the file.

当你不想重复自己,而是让你的代码干,只是尝试打开该文件,并让新的FileStream()抛出。然后,你可以捕捉异常,如果你愿意的话,重新抛出原来还是抛出一个应用程序特定的例外。

As you don't want to repeat yourself but instead keep your code DRY, just attempt to open the file and let new FileStream() throw. Then you can catch the exception, and if you wish, re-throw the original or throw an application-specific exception.

当然,调用文件.Exists()可以是合理的,但不是在这个模式。

Of course calling File.Exists() can be justified, but not in this pattern.

这篇关于如果我的方法抛出自己的异常,或是让.NET抛出,如果文件不存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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