Catching and Throwing Standard Exception Types
The following guidelines describe best practices for some of the most commonly used exceptions provided by the .NET Framework.
Do derive custom exceptions from the T:System.Exception class rather than the T:System.ApplicationException class.
It was originally thought that custom exceptions should derive from the ApplicationException class; however, this has not been found to add significant value. For more information, see Best Practices for Handling Exceptions.
Do throw a System.InvalidOperationException exception if in an inappropriate state. System.InvalidOperationException should be thrown if a property set or a method call is not appropriate given the object's current state. For example, writing to a System.IO.FileStream that has been opened for reading should throw a System.InvalidOperationException exception.
This exception should also be thrown when the combined state of a set of related objects is invalid for the operation.
Do throw System.ArgumentException or one of its subtypes if bad arguments are passed to a member. Prefer the most-derived exception type if applicable.
The following code example demonstrates throwing an exception when an argument is null (Nothing in Visual Basic).
Do set the System.ArgumentException.ParamName property when throwing System.ArgumentException or one of its derived types. This property stores the name of the parameter that caused the exception to be thrown. Note that the property can be set using one of the constructor overloads.
Do use value for the name of the implicit value parameter of property setters.
The following code example shows a property that throws an exception if the caller passes a null argument.
Do not allow publicly callable APIs to explicitly or implicitly throw System.NullReferenceException, System.AccessViolationException, System.InvalidCastException, or System.IndexOutOfRangeException. Do argument checking to avoid throwing these exceptions. Throwing these exceptions exposes implementation details of your method that may change over time.
Do not explicitly throw System.StackOverflowException. This exception should be explicitly thrown only by the common language runtime (CLR).
Do not catch System.StackOverflowException.
It is extremely difficult to programmatically handle a stack overflow. You should allow this exception to terminate the process and use debugging to determine the source of the problem.
Do not explicitly throw System.ExecutionEngineException.
Portions Copyright 2005 Microsoft Corporation. All rights reserved.
Portions Copyright Addison-Wesley Corporation. All rights reserved.
For more information on design guidelines, see the "Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries" book by Krzysztof Cwalina and Brad Abrams, published by Addison-Wesley, 2005.