S2166 — Classes named like "Exception" should extend "Exception" or a subclass

Language
C#
Type
Code smell
Severity
Major
Tags
convention, error-handling, pitfall

Why is this an issue?

Clear, communicative naming is important in code. It helps maintainers and API users understand the intentions for and uses of a unit of code. Using "exception" in the name of a class that does not extend Exception or one of its subclasses is a clear violation of the expectation that a class' name will indicate what it is and/or does.

Noncompliant code example


public class FruitException // Noncompliant - this has nothing to do with Exception
{
  private Fruit expected;
  private string unusualCharacteristics;
  private bool appropriateForCommercialExploitation;
  // ...
}

public class CarException // Noncompliant - does not derive from any Exception-based class
{
  public CarException(string message, Exception inner)
  {
     // ...
  }
}

Compliant solution


public class FruitSport // Compliant - class name does not end with 'Exception'
{
  private Fruit expected;
  private string unusualCharacteristics;
  private bool appropriateForCommercialExploitation;
  // ...
}

public class CarException: Exception // Compliant - correctly extends System.Exception
{
  public CarException(string message, Exception inner): base(message, inner)
  {
     // ...
  }
}

↑ Back to top