Secret ingredients to quality software


Do you catch and re-throw exceptions properly?

Last updated by Brady Stroud [SSW] on 17 Mar 2021 05:42 am (about 2 months ago) See History

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 {} 

catch (SomeException) {} 

catch { throw; } 

catch (SomeException) { throw; } 

Bad Example - Never use an empty catch block. Do something in the block or remove it.

catch (SomeException ex) { throw ex; } 

catch (SomeException ex) { someMethod(); throw ex; } 

Bad Example - Never re-throw exceptions by passing the original exception object. Wrap the exception or use throw; instead.

catch (SomeException ex) 

catch (SomeException ex) 
     SomeOtherException wrapperEx = new SomeOtherException("This is a wrapper exception", ex);
     throw wrapperEx; 

Good Example - Good code

Adam CoganAdam Cogan
Drew RobsonDrew Robson

We open source. This page is on GitHub