Skip to content

Gendarme.Rules.Exceptions.DoNotSwallowErrorsCatchingNonSpecificExceptionsRule(2.10)

Sebastien Pouliot edited this page Feb 9, 2011 · 3 revisions

DoNotSwallowErrorsCatchingNonSpecificExceptionsRule

Assembly: Gendarme.Rules.Exceptions
Version: 2.10

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.
Clone this wiki locally