Compartir a través de


Designing Custom Exceptions 

The following guidelines help ensure that your custom exceptions are correctly designed.

Avoid deep exception hierarchies.

For more information, see Types and Namespaces.

Do derive exceptions from System.Exception or one of the other common base exceptions.

Note that Catching and Throwing Standard Exception Types has a guideline that states that you should not derive custom exceptions from ApplicationException.

Do end exception class names with the Exception suffix.

Consistent naming conventions help lower the learning curve for new libraries.

Do make exceptions serializable. An exception must be serializable to work correctly across application domain and remoting boundaries.

For information about making a type serializable, see Serialization.

Do provide (at least) the following common constructors on all exceptions. Make sure the names and types of the parameters are the same those used in the following code example.

public class NewException : BaseException, ISerializable
{
    public NewException()
    {
        // Add implementation.
    }
    public NewException(string message)
    {
        // Add implementation.
    }
    public NewException(string message, Exception inner)
    {
        // Add implementation.
    }

    // This constructor is needed for serialization.
   protected NewException(SerializationInfo info, StreamingContext context)
   {
        // Add implementation.
   }
}

Do report security-sensitive information through an override of System.Object.ToString only after demanding an appropriate permission. If the permission demand fails, return a string that does not include the security-sensitive information.

Do store useful security-sensitive information in private exception state. Ensure that only trusted code can get the information.

Consider providing exception properties for programmatic access to extra information (besides the message string) relevant to the exception.

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.

See Also

Concepts

Choosing the Right Type of Exception to Throw

Other Resources

Design Guidelines for Developing Class Libraries
Design Guidelines for Exceptions