Sunday 12 June 2011

A few useful exception types

Sometimes it’s useful to throw exceptions from your code, for example if an incoming method argument is incorrect for some reason. Throwing Exception isn’t very specific so what should we throw and when? Here’s a quick aide-mémoire for a few exception types I use:

Exception type When to use it
ArgumentException The exception that is thrown when one of the arguments provided to a method is not valid.
InvalidOperationException The exception that is thrown when a method call is invalid for the object's current state.
FormatException The exception that is thrown when the format of an argument does not meet the parameter specifications of the invoked method.
NotImplementedException The exception that is thrown when a requested method or operation is not implemented.

References

http://msdn.microsoft.com/en-us/library/system.systemexception.aspx