Skip to content

Gendarme.Rules.Exceptions.DoNotSwallowErrorsCatchingNonSpecificExceptionsRule(git)

Sebastien Pouliot edited this page Mar 2, 2011 · 1 revision

DoNotSwallowErrorsCatchingNonSpecificExceptionsRule

Assembly: Gendarme.Rules.Exceptions
Version: git

Description

This rule will fire if a catch block catches System.Exception or System.SystemException but does not rethrow the original exception. This is problematic because you don't know what went wrong so it's difficult to know that the error was handled correctly. It is better to catch a more specific set of exceptions so that you do know what went wrong and do know that it is handled correctly.

Examples

Bad example:

try {
    File.Open ("foo.txt", FileMode.Open);
}
catch (Exception) {
    //Ooops  what's failed ??? UnauthorizedException, FileNotFoundException ???
}

Good example (catch a specific exception):

try {
    File.Open ("foo.txt", FileMode.Open);
}
catch (FileNotFoundException exception) {
    //I know that the system can't find the file.
}

Good example (catch all and rethrow):

try {
    File.Open ("foo.txt", FileMode.Open);
}
catch {
    Console.WriteLine ("An error has happened.");
    throw;  // You don't swallow the error, because you rethrow the original exception.
}

Notes

  • Prior to Gendarme 2.0 this rule was named DontSwallowErrorsCatchingNonspecificExceptionsRule.

Source code

You can browse the latest source code of this rule on github.com

Clone this wiki locally