Friday 27 April 2012

Why catch and rethrow Exception in C#?


Don't do this,
try {
...
}
catch(Exception ex)
{
   throw ex;
}
You'll lose the stack trace information...
Either do,
try { ... }
catch { throw; }
OR
try { ... }
catch (Exception ex)
{
    throw new Exception("My Custom Error Message", ex);
}
One of the reason you might want to rethrow is if your handling different exceptions e.g.
try
{
   ...
}
catch(SQLException sex)
{
   //Do Custom Logging 
   //Don't throw exception - swallow it here
}
catch(OtherException oex)
{
   //Do something else
   throw new WrappedException("Other Exception occured");
}
catch
{
   System.Diagnostics.Debug.WriteLine("Eeep! an error, not to worry, will be handled higher up the call stack");
   throw; //Chuck everything else back up the stack
}