Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-4027

Exceptions should provide standard constructors

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Implement the missing constructors for this exception.
    • Highlighting:
      Hide

      Exception class declaration

      Show
      Exception class declaration
    • Default Severity:
      Minor
    • Impact:
      Low
    • Likelihood:
      Low
    • Covered Languages:
      C#
    • Irrelevant for Languages:
      ABAP, C, C++, Cobol, CSS, Flex, HTML, Java, JavaScript, Objective-C, PHP, PL/I, PL/SQL, Python, RPG, Swift, T-SQL, TypeScript, VB.Net, VB6, XML
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      10min
    • Analysis Scope:
      Main Sources, Test Sources
    • FxCop:
      ImplementStandardExceptionConstructors, CA1032

      Description

      Exceptions types should provide the following constructors:

      • public MyException()
      • public MyException(string)
      • public MyException(string, Exception)
      • protected or private MyException(SerializationInfo, StreamingContext)

      That fourth constructor should be protected in unsealed classes, and private in sealed classes.

      Not having this full set of constructors can make it difficult to handle exceptions.

      Noncompliant Code Example

      using System;
      
      namespace MyLibrary
      {
        public class MyException // Noncompliant: several constructors are missing
        {
          public MyException()
          {
          }
        }
      }
      

      Compliant Solution

      using System;
      using System.Runtime.Serialization;
      
      namespace MyLibrary
      {
        public class MyException : Exception
        {
            public MyException()
            {
            }
      
            public MyException(string message)
                :base(message)
            {
            }
      
            public MyException(string message, Exception innerException)
                : base(message, innerException)
            {
            }
      
            protected MyException(SerializationInfo info, StreamingContext context)
                : base(info, context)
            {
            }
        }
      }
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              jeanchristophe.collet Jean-Christophe Collet (Inactive)
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: