Implement Standard Exception Ctors

ID

csharp.implement_standard_exception_ctors

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Best Practice

Language

CSharp

Tags

best_practice, exception-handling

Description

Reports Exception-derived classes that do not provide the three standard public constructors recommended by the .NET Framework Design Guidelines: (), (string message) and (string message, Exception innerException).

Rationale

Generic infrastructure code commonly creates or re-throws exceptions through one of those three constructors. Reflection-based test harnesses instantiate via (); rethrow / wrap patterns rely on (message, innerException); logging frameworks emit through (message). A custom exception that omits any of these shapes silently refuses to co-operate with that infrastructure and forces every caller to special-case it.

public class IncompleteException : Exception                                    // FLAW
{
    public IncompleteException(string message) : base(message) { }
    // missing () and (string, Exception)
}

public class CompleteException : Exception                                      // OK
{
    public CompleteException() { }
    public CompleteException(string message) : base(message) { }
    public CompleteException(string message, Exception innerException)
        : base(message, innerException) { }
}

Remediation

Add the three public constructors and delegate to the matching base constructor. Modern .NET no longer requires the legacy (SerializationInfo, StreamingContext) constructor; this rule does not flag its absence.