How to catch multiple exceptions at once in C#

Post author: Adam VanBuskirk
Adam VanBuskirk
5/14/23 in
Tech
C#

Let’s look at how to best catch multiple, specific exceptions in C#. For example, we start with the below code.

try
{
    WebId = new Guid(queryString["web"]);
}
catch (FormatException)
{
    WebId = Guid.Empty;
}
catch (OverflowException)
{
    WebId = Guid.Empty;
}

This code catches the FormatException and the OverflowException, but notice how it repeats the WebId = Guid.Empty code. We can improve this by using a switch statement.

We can eliminate the redundancy by catching both the FormatException and OverflowException exceptions with a single catch block, as both of these exceptions indicate that the Guid parsing failed due to an invalid format or a number that is too large or too small.

Here’s an example of how you can improve the code:

try
{
    WebId = new Guid(queryString["web"]);
}
catch (Exception ex) when (ex is FormatException || ex is OverflowException)
{
    WebId = Guid.Empty;
}

In this updated code, the catch block uses a when clause to catch only FormatException and OverflowException exceptions, which are the two types of exceptions that can occur when parsing a Guid from a string. Any other exceptions that may occur during the Guid parsing will not be caught by this catch block and will be propagated up the call stack.

By catching both exceptions with a single catch block, we avoid duplicating the code to set the WebId to Guid.Empty in two places, which makes the code more maintainable and easier to read.

Sign up today for our weekly newsletter about AI, SEO, and Entrepreneurship

Leave a Reply

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


Read Next




© 2024 Menyu LLC