I typically agree with most code analysis warnings, and I try to adhere to them. However, I'm having a harder time with this one:
CA1031: Do not catch general exception types
I understand the rationale for this rule. But, in practice, if I want to take the same action regardless of the exception thrown, why would I handle each one specifically? Furthermore, if I handle specific exceptions, what if the code I'm calling changes to throw a new exception in the future? Now I have to change my code to handle that new exception. Whereas if I simply caught Exception
my code doesn't have to change.
For example, if Foo calls Bar, and Foo needs to stop processing regardless of the type of exception thrown by Bar, is there any advantage in being specific about the type of exception I'm catching?
Maybe a better example:
public void Foo()
{
// Some logic here.
LogUtility.Log("some message");
}
public static void Log()
{
try
{
// Actual logging here.
}
catch (Exception ex)
{
// Eat it. Logging failures shouldn't stop us from processing.
}
}
If you don't catch a general exception here, then you have to catch every type of exception possible. Patrick has a good point that OutOfMemoryException
shouldn't be dealt with this way. So what if I want to ignore every exception but OutOfMemoryException
?
OutOfMemoryException
? Same handling code as everything else?OutOfMemoryError
, which is separate from theException
inheritance tree for that very reason