Is there a standard FxCop rule that detects throwing new exceptions without setting InnerException?

207 Views Asked by At

Our (pretty large) code base has a few of these constructs:

try {
    DoSomething();
}
catch (Exception e) {
    CleanUp();
    throw new MoreSpecificException();
}

And I want to ensure that we throw a new exception with InnerException set in most of these cases.

Is there a standard FxCop rule that detects throwing new exceptions without setting InnerException? My research (googling) indicates that no such rule exists.

And if not, how can such a rule be created? (I have never before created a custom FxCop rule).

I also had a look at the Gendarme tool, but could not find anything like what I need there.

The FxCop rules are run by SonarQube, BTW.

1

There are 1 best solutions below

6
On

Yes, this is possible with FxCop. A guide to creating custom rules can http://www.binarycoder.net/fxcop/index.html.

FWIW, I'd recommend creating a "do not eat exceptions" rule instead, with throwing a new exception with the original as an inner exception being one of the "not eating" patterns recognized by the rule. This would be more generally useful than an "every throw exception must have an inner exception rule", as well as avoiding a potentially large number of false positives with the latter rule.