General Performance Tip: Handling Exceptions

While delivering my presentation for the Rock Your Code: Code and App Performance for Microsoft .NET session at the Silicon Valley Code Camp (recognized as the largest community-run conference globally), an attendee posed an intriguing question regarding the performance implications of using the When() clause when catching exceptions. Captivated by the inquiry, I performed performance testing to offer an insightful response.

Two Approaches to Exception Handling

Since the inception of .NET, the conventional approach to handling code exceptions has been a crucial aspect of programming. This practice is vital to safeguard the application or service from unexpected disruptions.

try
{
    //Code that could cause an Exception
}
catch (ArgumentNullException nullEx)
{
    return nullEx.Message;
}
catch (ArgumentOutOfRangeException outOfRangeEx)
{
    return outOfRangeEx.Message;
}

A more recent and simplified method for handling exceptions is by utilizing the When() clause, as demonstrated below:

try
{
    //Code that could cause an Exception
}
catch (Exception ex) when (ex is ArgumentNullException || 
                           ex is ArgumentOutOfRangeException)
{
    return ex.Message;
}

Benchmark Results

Here are the results for the two methods of trapping exceptions mentioned above. These tests demonstrate that when capturing multiple similar exceptions, using try/catch is 1.03 times more efficient.

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.