Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

General Exception Handling in C#

I'm running some code through FxCop and am currently looking at clearing all of the non-breaking violations.

The code itself has a few instances of try/catch blocks which just catch general exceptions;

try
{
    // Some code in here that could throw an exception
}
catch(Exception ex)
{
    // Exception Thrown ... sort it out!
}

Now we all know this is is bad practice but I thought I knew how to do it properly - but FxCop has other ideas!

Suppose that the code in the try block could throw an IO Exception - and only an IO exception. There should be nothing wrong with doing this:

try
{
    // Code in here that can only throw an IOException
}
catch (System.IO.IOException ioExp)
{
    // Handle the IO exception or throw it
}
catch (System.Exception ex)
{
    // Catch otherwise unhandled exception
}

But FxCop disagrees with me ... it still flags this as a violation because I'm catching System.Exception.

Is this really bad practice or should/can I safely ignore this violation?

like image 201
DilbertDave Avatar asked Oct 27 '09 10:10

DilbertDave


2 Answers

I agree with FxCop and most of the other answers here: don't catch System.Exception ever, unless it is at the highest level in your application to log unexpected (and thus fatal) exceptions and then bomb the application. Also check out this question that's basically about the same thing.

Some other valid exceptions might be:

  • To catch exceptions for the sole reason of rethrowing a more descriptive one.
  • In unit test code that needs something more complex than an ExpectedExceptionAttribute.
  • In facade library code that only exists to shield callers from intricacies of calling some external (web) service, while never actually failing itself, no matter how badly the external system might go down.
like image 111
peSHIr Avatar answered Oct 10 '22 11:10

peSHIr


I agree with the other answers that catch (Exception ex) is fine if you either

  1. just log and rethrow the exception or
  2. do it at the highest level (UI) of your application.

There is one more situation that comes to my mind where it could make sense: When writing unattended code (e.g. some system service), it can make perfect sense to keep the program running if some (well-defined) sub-task fails for whatever reason. Of course, care must be taken to ensure that the reason for the problem gets logged and (maybe) the task is tried again after some time.

like image 42
Heinzi Avatar answered Oct 10 '22 11:10

Heinzi