Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

exception

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?

like image 415
fhnaseer Avatar asked Oct 05 '15 14:10

fhnaseer


People also ask

When should a method throw an exception?

In short: You should throw an exception if a method is not able to do the task it is supposed to do.

Which of the following should not throw an exception?

I also know that the following cannot throw exceptions either: Destructors. Reading/writing primitive types.

What happens if you don't catch an exception C#?

In C#, the catch keyword is used to define an exception handler. If no exception handler for a given exception is present, the program stops executing with an error message. Don't catch an exception unless you can handle it and leave the application in a known state.

Can a method throw exception in C#?

In Java, you must either handle an exception or mark the method as one that may throw it using the throws keyword. C# does not have this keyword or an equivalent one, as in C#, if you don't handle an exception, it will bubble up, until caught or if not caught it will terminate the program.


1 Answers

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.

like image 128
CodeCaster Avatar answered Sep 22 '22 18:09

CodeCaster