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
Make a one-time donation
Make a monthly donation
Make a yearly donation
Choose an amount
Or enter a custom amount
Your contribution is appreciated.
Your contribution is appreciated.
Your contribution is appreciated.
DonateDonate monthlyDonate yearlyIf 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.
