Search code examples
c#exception

How do I chose the most appropriate type of exception to throw?


There are already lots of questions on SO about exceptions, but I can't find one that answers my question. Feel free to point me in the direction of another question if I've missed it.

My question is quite simple: how do other (C#) developers go about choosing the most appropriate type of exception to throw? Earlier I wrote the following code:

    if (Enum.IsDefined(enumType, value))
    {
        return (T)Enum.Parse(enumType, value);
    }
    else
    {
        throw new ArgumentException(string.Format("Parameter for value \"{0}\" is not defined in {1}", value, enumType));
    }

I have since realised that throwing an InvalidEnumArgumentException would probably have been more appropriate had I known of its existence at the time.

Is there an authoritative resource available that helps developers chose exception types, or is it simply a matter of experience?

Edit

I've given the points to Noldorin for providing a range of ideas in a well thought-out answer. The points could have gone to any one of you really - thanks for all the suggestions.


Solution

  • I would say it's just down to experience. There's still new exceptions I discover every so often, and I've been working with many aspects of .NET for a while now! What would you want this source to tell you, anyway? Choosing the appropriate exception type would seem highly context-specific, so I'm doubtful over the level of advice it could offer. Listing the more common ones would be most it could provide. The names and Intellisense descriptions of the exception types typically explain with good clarity their usage scenarios.

    My recommendation is simply to familiarize yourself with all of the fundamental ones (specifically, those in System, System.IO, and any other namespaces you often use), and learn the others along the way. I find that I generally get away using just a small number. If you accidentally use a more generic exception type when there already exists a more specific one in the BCL, then it's no great crime, and can be changed later easily enough. To be honest, for any error that's particularly specific, you will often need to create your own class inheriting from Exception anyway.

    Hope that helps.

    Edit: If you want a brief guide to the very common ones, see the Common Exception Classes page on MSDN.