Throwing exceptions the right way

Use ReSharper? Notice every time ReSharper sees code like this:

catch (Exception ex)
{
    // some exception handling, or logging here
    throw ex;
}

it complains, and tells you to get rid of the ex for the reason ‘Exception rethrow possibly intended’?

The reason ReSharper is warning you about an ‘exception rethrow’ is that when you rethrow an exception it replaces the stack trace of the original exception with the current location. So if you print the stack trace further up the code you will not be able to see the statement which caused the exception in the first place!

For this reason, you should ALWAYS use this instead:

catch (Exception ex)
{
    // exception handling
    throw;
}

Handling multiple exceptions

Further on exception handling, if your code might throw multiple types of exceptions and you want to handle the exceptions differently then you can build up a hierarchy of catch clauses from the most specific (SqlException e.g.) at the top, to the least specific (Exception) at the bottom like this:

try
{
    // do something that can might throw an exception
}
catch (SqlException sqlEx)
{
    // retry on timeout or deadlock for example?
}
catch (Exception ex)
{
    // handle more generic exception
}
finally
{
    // put any clean up operations here
}

It’s worth noting that, if you are catching the more general exceptions further up the chain your exception handling code for more specific types of exception lower down the list will never be called! But fortunately tools like ReSharper will warn you first :-)

Another thing you might want to consider is to wrap the built-in exception types into a custom Exception type and maybe use an enum to categorise the different exceptions into well defined types that your application understands (e.g. ServerError, FeedError, DatabaseError, etc.).

In the case of WCF services, you can also specify fault contracts for each operation and in your catch clauses on the server side wrap all exceptions into faults so when exceptions happen they don’t fault your channel. For more on WCF error handling and fault conversion, have a look at this article.

 

Learn to build Production-Ready Serverless applications

Want to learn how to build Serverless applications and follow best practices? Subscribe to my newsletter and join over 5,000 AWS & Serverless enthusiasts who have signed up already.

Leave a Comment

Your email address will not be published. Required fields are marked *