CA1032: Implement standard exception constructors

Note

This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

Item Value
TypeName ImplementStandardExceptionConstructors
CheckId CA1032
Category Microsoft.Design
Breaking Change Non-breaking

Cause

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

Rule Description

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

How to Fix Violations

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

When to Suppress Warnings

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.

Example

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.
      }
   }  
}