I have a method which takes a directory path as a string. In the beginning of the method it checks if this path exists and if not it should throw an exception. I'm thinking it should maybe throw a DirectoryNotFoundException
or something instead of a less specific ArgumentException
.
I read the msdn documentation of that DirectoryNotFoundException
and it says that
DirectoryNotFoundException
uses theHRESULT COR_E_DIRECTORYNOTFOUND
which has the value0x80070003
.
I don't know what that means exactly, and it looks a bit scary... should I still throw that exception, or should I stick to a regular ArgumentException
? Or should I stick to the ArgumentException
simply because it is an argument I am complaining about? Or?
public void MakeFunOf(string path)
{
if(!Directory.Exists(path))
throw new WhatException();
TellJokeAbout(path);
PointAndLaughAt(path);
}
If you expect the developer to check for the existence of the directory before calling your method, use ArgumentException. If you want the developer to have the choice of handling the missing directory, use DirectoryNotFound exception.
In other words, "Is it a bug that the developer told me to access a directory that didn't exist?"
Personally, I'd use the DirectoryNotFound exception.
In my opinion you should check for the correctnes of the argument and throw an ArgumentException then after the check throw an DirectoryNotFoundException. It is a big difference if no argument was given or only a wrong path was specified.
void CheckDir(string path)
{
if(String.IsNullOrEmpty(path))
{
throw new ArgumentException("Path not specified.");
}
if(!Directory.Exists(path))
{
throw new DirectoryNotFoundException();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With