Alex Rivera | Logout

Eating Exceptions in c# om nom nom

Asked 2010-10-07T17:46:12.390
10

Given that eating exceptions is always bad juju and re-throwing the exception loses the call stack, what's the proper way to re-factor the following?

Eating Exceptions:

try
{
  … do something meaningful
}
catch(SomeException ex)
{
   // eat exception
}
Edit
Report

2 Answers

30
try
{
 ...
}
catch(SomeException e)
{
 //Do whatever is needed with e
 throw; //This rethrows and preserves call stack.
}
answered 2010-10-07T17:48:26.507
7

Catch and handle specific types of exceptions. Good practice is to not just catch System.Exception. A robust routine will strongly type the exceptions it knows how to handle.

Exceptions shouldn't be used for control flow, but there are often specific unwind procedures that need to be taken based on the type of exception.

Depending on the specific type, you may or may not choose to rethrow it. For example, an ASP parsing exception being thrown to an error page that USES the code causing the exception will cause an infinite loop.

try
{

}
catch( FileIOException )
{
    // unwind and re-throw as determined by the specific exception type
}
catch( UnauthorizedAccessException )
{
    // unwind and re-throw as determined by the specific exception type
}
catch( SomeOtherException )
{
    // unwind and re-throw as determined by the specific exception type
}
catch( Exception )
{
   // log and re-throw...add your own message, capture the call stack, etc.

   // throw original exception
   throw;

   // OR, throw your own custom exception that provides more specific detail and captures
   // the original exception as the inner exception
   throw new MyStronglyTypedException();
}
finally
{
     // always clean up
}
answered 2010-10-07T17:52:47.370

Your Answer