Do not raise too general exception types

Rule ND2207 .NET Framework Usage / System

These exception types are too general to inform the user:

- System.Exception

- System.ApplicationException

- System.SystemException

Throwing them from a library compels clients to catch all exceptions, including unknown ones they can't handle. Matches methods instantiating such exceptions.

How to fix

Throw a more derived framework exception type, or your own type deriving from System.Exception.

Estimated Debt: 15 minutes per method plus 5 minutes per too general exception type instantiated.

CQLinq source

This rule is written in CQLinq, C# LINQ over the NDepend code model. It ships with every new NDepend project: you can read it, adapt it, or use it as a starting point for your own custom rules.

// <Name>Do not raise too general exception types</Name>
// <Id>ND2207:DoNotRaiseTooGeneralExceptionTypes</Id>
       
warnif count > 0 

let tooGeneralExceptionTypes = ThirdParty.Types.WithFullNameIn(
   "System.Exception", 
   "System.ApplicationException",
   "System.SystemException")

from m in JustMyCode.Methods.ThatCreateAny(tooGeneralExceptionTypes)
// Make sure we don't match constructor of exception types
// that actually instantiate System.Exception.
where !m.IsConstructor || tooGeneralExceptionTypes.All(t => !m.ParentType.DeriveFrom(t))
let exceptionsCreated = tooGeneralExceptionTypes.Where(t => m.IsUsing(t))
select new {
   m,
   exceptionsCreated,
   Debt = (15 + 5*exceptionsCreated.Count()).ToMinutes().ToDebt(),
   Severity = Severity.High
}

//<Expl>
// The *{0}* creates an instance of the *{1}*. Throwing such exception compels client code 
// to catch all exceptions, including unknown exceptions that they 
// do not know how to handle.
//</Expl>

//<Desc>
// These exception types are too general to inform the user:
//
// - System.Exception
//
// - System.ApplicationException
//
// - System.SystemException
//
// Throwing them from a library compels clients to catch all exceptions,
// including unknown ones they can't handle. Matches methods instantiating
// such exceptions.
//</Desc>

//<HowToFix>
// Throw a more derived framework exception type, or your own type deriving
// from *System.Exception*.
//
// Estimated Debt: 15 minutes per method plus 5 minutes per too general
// exception type instantiated.
//</HowToFix>

.NET Framework Usage / System: all 12 items