Do you catch and re-throw exceptions properly?

Last updated by Ben Neoh [SSW] 6 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 and rethrow where you can usefully add more information that would save a developer having to work through all the layers to understand the problem.

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.

Using throw ex resets the stack trace, obscuring the original the error and may hide highly valuable information to debug this exception.

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

Good Example - Calling throw

If you are following the Clean Architecture pattern - catching and rethrowing is useful for preventing your Infrastructure details from leaking into your Application e.g. we use a SQL server

catch (SqlException ex) when (ex.Number == 2601)
{
     throw new IdAlreadyTakenException(ex);
}

Good Example - By rethrowing a specific exception, my application code now doesn't need to know that there is a SQL database or the magic numbers that SQL exceptions use

We open source. Powered by GitHub