0
0
CsharpHow-ToBeginner · 3 min read

How to Use 'when' in Catch Blocks in C#

In C#, you can use the when keyword in a catch block to add a condition that filters which exceptions the block handles. This allows you to catch exceptions only when a specific condition is true, making error handling more precise and readable.
📐

Syntax

The when keyword is used after the exception type in a catch block to specify a condition that must be true for the catch block to execute.

Structure:

  • catch (ExceptionType ex) when (condition): Catches exceptions of ExceptionType only if condition evaluates to true.
csharp
try
{
    // code that may throw
}
catch (ExceptionType ex) when (condition)
{
    // handle exception only if condition is true
}
💻

Example

This example shows how to catch a DivideByZeroException only when the divisor is zero, using a variable captured outside the try block.

csharp
using System;

class Program
{
    static void Main()
    {
        int divisor = 0;
        try
        {
            int result = 10 / divisor;
        }
        catch (DivideByZeroException ex) when (divisor == 0)
        {
            Console.WriteLine("Caught DivideByZeroException because divisor is zero.");
        }
        catch (DivideByZeroException ex)
        {
            Console.WriteLine("Caught DivideByZeroException for other reasons.");
        }
    }
}
Output
Caught DivideByZeroException because divisor is zero.
⚠️

Common Pitfalls

  • Using when without a condition or with a condition that always evaluates to false means the catch block will never run.
  • Variables used in the when condition must be in scope and accessible.
  • Do not put complex logic in the when condition; keep it simple to avoid confusion.
  • Remember that exceptions not matching the when condition will continue to look for other catch blocks or propagate.
csharp
try
{
    // code
}
catch (Exception ex) when (false) // This catch block never runs
{
    // unreachable code
}

// Correct usage:
try
{
    // code
}
catch (Exception ex) when (ex.Message.Contains("specific"))
{
    // handle only if message contains "specific"
}
📊

Quick Reference

Use when in catch to filter exceptions by condition.

  • Place when (condition) after the exception type.
  • Condition must be a boolean expression.
  • Helps write cleaner and more specific error handling.

Key Takeaways

Use when in catch blocks to handle exceptions only if a condition is true.
The condition in when must be a boolean expression accessible in the catch scope.
Exceptions not matching the when condition will be passed to other catch blocks or propagate.
Keep when conditions simple to maintain clear and readable code.
Using when improves precision in exception handling and avoids unnecessary catch executions.