If I need to throw an exception from within my application which of the built-in .net exception classes can I use? Are they all fair-game? When should I derive my own?
ApplicationException
SystemException
ArgumentException
ArgumentNullException
FormatException
NotSupportedException
NotImplementedException
I use the ArgumentException (and it's 'friends') regularly.
NotSupported and NotImplemented are also common.
http://blogs.msdn.com/brada/archive/2005/03/27/402801.aspx
Comments on that post are also useful.
I think you can throw every exception you like.
if it's wise is another matter ;)
You can create and throw pretty much any of them, but you generally shouldn't. As an example, the various argument validation exceptions (ArgumentException, ArgumentNullException, ArgumentOutOfRangeException, etc) are suitable for use in application code, but AccessViolationException isn't. ApplicationException is provided as a suitable base class for any custom exception classes you may require.
See this MSDN article for a list of best practices - it refers to handling exceptions, but also contains good advice on creating them...
On the subject of System.Exception
and System.ApplicationException
: The latter was meant to be used as the base class of all custom exceptions. However, this hasn't been enforced consistently from the beginning. Consequently, there's a controversy whether this class should be used at all rather than using System.Exception
as the base class for all exceptions.
Whichever way you decide, never throw an instance of these two classes directly. It's actually a pity that they aren't abstact
. For what it's worth, always try using the most specific exception possible. If there is none to meet your requirement, feel free to create your own. In this case, however, make sure that your exception has a benefit over existing exceptions. In particular, it should convey its meaning perfectly and provide all the information necessary to handle the situation in a meaningful manner.
Avoid to create stub exceptions that don't do anything meaningful. In the same vein, avoid creating huge exception class hierarchies, they're rarely useful (although I can imagine a situation or two where I would use them … a parser being one of them).