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.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!
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.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!