C#

Using the when Keyword in C# While Handling Exceptions

In this article, we are going to learn why and how to use the when keyword within try-catch blocks while handling exceptions in C#.

We cannot avoid the occurrence of exceptions in the life cycle of an application. An exception is a problem that appears unexpectedly from our codebase. Exception handling is the process of building a system that can detect and manage exceptions. Exceptions that are not handled properly can completely disrupt the flow of our application.

To learn more about exceptions and how to properly handle them, you can check out our Exception Handling in C# and Try-Catch Block in C# articles.

To download the source code for this article, you can visit our GitHub repository.

Let’s start.

Why Do We Need the when Keyword in try-catch Blocks in C#

A typical try-catch block permits the use of multiple catch statements as a form of exception filtering. The when keyword takes this further. It lets us specify a boolean condition that must be true in order for an exception handler to be enforced.

That said, let’s inspect the syntax for using the when keyword in C#:

try
{
    //Code that could cause an exception
} 
catch (Exception e) when ( boolean expression)
{
    throw;
}

The when keyword allows us to have multiple instances of the same exception filter in a try-catch block.

That said, let’s create a simple application that collects input from a user, and depending on the user input, creates several triggers for a FormatException:

try
{
    Console.WriteLine("Please enter your 8-digit special number");
    ConvertToInt(Console.ReadLine()!);

    Console.WriteLine("Would you like to part of a lottery? True or False");
    ConvertToBool(Console.ReadLine()!);

    Console.WriteLine("Please enter date of birth (Format => Friday, April 10, 2009)");
    ConvertToDateTime(Console.ReadLine()!);

    Console.WriteLine("Please enter your guid password");
    ConvertToGuid(Console.ReadLine()!);
}

The when keyword allows us to have different catch statements that expect the same kind of exception: 

catch (FormatException ex) when (ex.Message.Contains("Input string was not in a correct format"))
{                
    Console.WriteLine(ex.Message);
    Console.Write("Special number error");
    throw;
}
catch (FormatException ex) when (ex.Message.Contains("not recognized as a valid Boolean"))
{
    Console.WriteLine(ex.Message);
    Console.Write("Lottery participant error");
    throw;
}
catch (FormatException ex) when (ex.Message.Contains("not recognized as a valid DateTime"))
{                
    Console.WriteLine(ex.Message);
    Console.Write("Date of birth error");                
    throw;
}
catch (FormatException ex) when (ex.Message.Contains("Format string can be only"))
{
    Console.Write(ex.Message);
    Console.Write($"{Environment.NewLine}Guid error");                
    throw;
}
catch
{
    throw;
}

In our case, we have exception handlers that could be executed depending on the error message.

Multiple Exceptions in the Same Catch Block

We can also use the when keyword to handle multiple exceptions in a single catch block:

try
{
    Console.WriteLine($"{Environment.NewLine}Please enter your 8-digit special number");
    ConvertToInt(Console.ReadLine()!);

    Console.WriteLine($"Would you like to part of a lottery? True or False{Environment.NewLine}");
    ConvertToBool(Console.ReadLine()!);
}
catch (FormatException ex) when (ex.Message.Contains("correct format") || ex.Message.Contains("valid Boolean"))
{
    Console.WriteLine(ex.Message);
    Console.Write("Error!!");
    throw;
}
catch
{
    throw;
}

As we can see, we can shorten our codebase by packing exceptions using the when keyword.

For more information on Catching multiple exceptions, you can check out our Catch Multiple Exceptions article.

Conclusion:

In this article, we learned about using the when keyword while catching exceptions in C#. We also learned that we can use when within try-catch blocks to handle generic exceptions in a variety of ways.

Code Maze

View Comments

  • Great Article! I refactoring some exception handling that I had recently written to use the new when keyword, and it worked a treat! Thank you for this great share! :)

    • You are most welcome. I am glad you liked the article. Thanks for the comment.

  • You should never match based on the message because at least .NET Exception messages are localized. Your code will break on all non English locale installations. The "normal" usage of exception filters is taking a memory dump, or capturing context. Other uses are brittle because you never know if the error condition happens also in the code of your when handler (e.g. OutOfMemoryException?).

Share
Published by
Code Maze

Recent Posts

HttpClient vs RestSharp – Which One to Use in .NET

HttpClient and RestSharp are HTTP Client libraries that we can use to consume APIs. Working…

Updated Date Jul 7, 2022

Testing Repository Pattern Using Entity Framework

Unit Testing is extremely important for creating robust software. It's very simple in principle but…

Updated Date Jul 6, 2022

Shell Sort in C#

Have you ever needed to sort a list of items, but didn't want to use…

Updated Date Jul 5, 2022

How to Resolve Instances With ASP.NET Core DI

In ASP.NET Core dependency injection, we usually register injectable dependencies at the start of our…

Jul 4, 2022

Ranges and Indices in C#

In this article, we are going to learn more about ranges and indices in C#,…

Updated Date Jul 2, 2022

Code Maze Weekly #128

Issue #128 of the Code Maze weekly. Check out what's new this week and enjoy…

Updated Date Jul 1, 2022