Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

c# - Should my method throw its own exception, or let .NET throw if a file doesn't exist?

Here is my code:

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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.

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...