Home
Do you catch and re-throw exceptions properly?
  v3.0 Posted at 8/09/2014 10:35 AM by Drew Robson

​A good catch and re-throw will make life easier while debugging, a bad catch and re-throw will ruin the exception's stack trace and make debugging difficult.

catch {} 
(Never use an empty catch block. Do something in the block or remove it.)

catch (SomeException) {} 
(Never use an empty catch block. Do something in the block or remove it.)

catch { throw; } 
(Never use an empty catch block. Do something in the block or remove it.)
catch (SomeException) { throw; }
(Never use an empty catch block. Do something in the block or remove it.)
catch (SomeException ex) { throw ex; } (Never re-throw exceptions by passing the original exception object. Wrap the exception or use throw; instead.) catch (SomeException ex) { someMethod(); throw ex; } (Never re-throw exceptions by passing the original exception object. Wrap the exception or use throw; instead.)
Bad Example - Bad code
catch (SomeException ex) 
{ 
     someMethod(); 
     throw; 
}

catch (SomeException ex) 
{ 
     someMethod(); 
     SomeOtherException wrapperEx = new SomeOtherException("This is a wrapper exception", ex);
     throw wrapperEx; 
}
Good Example - Good code

We have a program called SSW Code Auditor to check for this rule.

Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address:

    Comments:

    Note: Social Media login for Yotpo is not working in IE or Safari, please use Chrome. We are waiting for Yotpo to fix it.