Export (0) Print
Expand All
Expand Minimize

CA1032: Implement standard exception constructors

TypeName

ImplementStandardExceptionConstructors

CheckId

CA1032

Category

Microsoft.Design

Breaking Change

Non-breaking

A type extends System.Exception and does not declare all the required constructors.

Exception types must implement the following constructors:

  • public NewException()

  • public NewException(string)

  • public NewException(string, Exception)

  • protected or private NewException(SerializationInfo, StreamingContext)

Failure to provide the full set of constructors can make it difficult to correctly handle exceptions. For example, the constructor that has the signature NewException(string, Exception) is used to create exceptions that are caused by other exceptions. Without this constructor you cannot create and throw an instance of your custom exception that contains an inner (nested) exception, which is what managed code should do in such a situation. The first three exception constructors are public by convention. The fourth constructor is protected in unsealed classes, and private in sealed classes. For more information, see CA2229: Implement serialization constructors

To fix a violation of this rule, add the missing constructors to the exception, and make sure that they have the correct accessibility.

It is safe to suppress a warning from this rule when the violation is caused by using a different access level for the public constructors.

The following example contains an exception type that violates this rule and an exception type that is correctly implemented.

using System;
using System.Runtime.Serialization;
namespace DesignLibrary
{
   // Violates rule ImplementStandardExceptionConstructors. 
   public class BadException : Exception
   {
      public BadException()
      {
         // Add any type-specific logic, and supply the default message.
      }

   }  

   [Serializable()]
   public class GoodException : Exception
   {
      public GoodException()
      {
         // Add any type-specific logic, and supply the default message.
      }

      public GoodException(string message): base(message) 
      {
         // Add any type-specific logic.
      }
      public GoodException(string message, Exception innerException): 
         base (message, innerException)
      {
         // Add any type-specific logic for inner exceptions.
      }
      protected GoodException(SerializationInfo info, 
         StreamingContext context) : base(info, context)
      {
         // Implement type-specific serialization constructor logic.
      }
   }  
}
Show:
© 2014 Microsoft