Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Should I throw an ArgumentException or a DirectoryNotFoundException?

Tags:

c#

exception

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 the HRESULT COR_E_DIRECTORYNOTFOUND which has the value 0x80070003.

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);
}
like image 273
Svish Avatar asked Jul 02 '09 07:07

Svish


2 Answers

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.

like image 180
Talljoe Avatar answered Sep 19 '22 16:09

Talljoe


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();
  }
}
like image 40
Oliver Friedrich Avatar answered Sep 20 '22 16:09

Oliver Friedrich