Throwing exceptions the right way

Yan Cui

I help clients go faster for less using serverless technologies.

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.


Whenever you’re ready, here are 3 ways I can help you:

  1. Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game.
  2. Consulting: If you want to improve feature velocity, reduce costs, and make your systems more scalable, secure, and resilient, then let’s work together and make it happen.
  3. Join my FREE Community on Skool, where you can ask for help, share your success stories and hang out with me and other like-minded people without all the negativity from social media.

 

Leave a Comment

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