How do I chose the most appropriate type of exception to throw?
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.
Krzysztof Cwalina has a good post on this see chapter "1.1.1 Choosing the Right Type of Exception to Throw"
PS Consider subscribing to his blog. Good reading!
To answer your question: InvalidEnumArgumentException
because throw the most specific (the most derived) exception that makes sense.
AND callers that catch ArgumentException, catch InvalidEnumArgumentException too...
Common Exception Types and their Explanations
I think this will probably help you find out what the most appropriate exceptions for you to use are. You can also look into the MSDN documentation for more information on the Exception class and all of its types if you need.
- MSDN Exception Class (System)
- MSDN SystemException Class (System) - More thorough list of exception types