Skip to content

catch with when condition

Context: The when keyword in a catch clause introduces an exception filter. The catch block is entered only if the filter condition evaluates to true. This is more powerful than catching and rethrowing because the stack is not unwound if the condition is false, preserving debugging information.

using System;
using System.Net.Http;
class Program
{
static async Task Main()
{
try
{
using var client = new HttpClient();
var response = await client.GetAsync("https://httpstat.us/404");
response.EnsureSuccessStatusCode();
}
catch (HttpRequestException ex) when (ex.Message.Contains("404"))
{
Console.WriteLine("Resource not found (404) – handled gracefully.");
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Other HTTP error: {ex.Message}");
}
}
}
Terminal window
dotnet run
Resource not found (404) – handled gracefully.
  • The condition is evaluated in the context of the catch block.
  • You can use methods in the condition, but they should not throw exceptions.
  • Filters are evaluated before any outer catch blocks.

Database retry logic – Catch SqlException only when the error number indicates a transient failure (e.g., timeout or deadlock).
See .NET docs on when filter.