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

c#, exception

Solution

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.

Problem

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); } ```

Original source