Read the syntax
Handle only matching error conditions without catching and rethrowing unrelated failures.
The filter matches code 429 and selects the narrow handler.
What it is and why to use it
One exception type can describe several recoverable and unrecoverable conditions. An exception filter adds a boolean predicate to a catch clause so that the handler runs only for relevant cases. This keeps a narrow recovery policy near the handler instead of accepting every exception of the type and then deciding what to do inside it.
How it works
Write catch (SomeException error) when (condition). When the condition is false, the runtime continues searching for another handler. Filters run during handler selection before unwinding to the chosen catch. Keep predicates simple and avoid side effects; a filter is for classification, not for performing recovery work.
Common mistakes and limitations
Do not parse arbitrary exception message text as a stable protocol when a typed property or error code is available. Do not swallow every exception through a broad filter. If a filter itself throws, it does not become the ordinary body of the intended catch; keep filter logic dependable.
Run the examples locally
These complete Program.cs examples use a .NET 10 console project with the C# language version set to 12.0, nullable checking enabled and implicit usings disabled. They use standard .NET libraries and need no extra NuGet packages. This is the verified environment, not a claim that every API requires .NET 10 or works unchanged in .NET Framework, Unity or other runtimes.
Install a supported .NET 10 SDK, create the console project, replace its project file with the settings below, then replace Program.cs with one complete example at a time. Build and run from the project folder. using directives bring namespaces into scope; top-level statements form the program’s entry point, and any helper types follow those statements. Console.WriteLine writes terminal output. Do not combine examples that declare the same type names.
C# in Codectionary’s Playground is editing-only: it does not compile or execute these programs. Run them with the local .NET SDK to reproduce the expected output. Async examples use controlled in-process operations rather than live network services or timing-sensitive delays.
Create and enter a project
dotnet new console -n CSharpExample --framework net10.0
cd CSharpExampleCSharpExample.csproj settings used for these examples
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>12.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
</Project>Build and run after saving one example in Program.cs
dotnet build
dotnet run --no-buildContinue learning
Change one input and predict the result before running it. Follow the related guides to connect this topic with the surrounding language features.
Syntax
catch (RequestFailure error) when (error.Code == 429) { /* chosen policy */ }Examples
Choose a handler by a typed error code
Simulate a failure in-process without contacting an external service.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
try { throw new RequestFailure(429); }
catch (RequestFailure error) when (error.Code == 429) { Console.WriteLine("Rate-limited case"); }
class RequestFailure(int code) : Exception {
public int Code { get; } = code;
}
- The custom exception carries a numeric classification separately from its message.
- The filter matches code 429 and selects the narrow handler.
- This is a classification demonstration, not a real retry policy; real retries also need cancellation, limits and service-specific guidance.
- Expected output: Rate-limited case
- Classify using stable typed data.
Let an unmatched failure reach another handler
Show that a false filter does not consume the exception.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
try {
try { throw new RequestFailure(500); }
catch (RequestFailure error) when (error.Code == 429) { Console.WriteLine("Special case"); }
} catch (RequestFailure) {
Console.WriteLine("Outer handler");
}
class RequestFailure(int code) : Exception { public int Code { get; } = code; }
- The inner catch recognises the exception type but its filter is false for 500.
- No inner catch body runs, so handler search continues outward.
- The outer handler receives the failure. Unmatched failures are not silently treated as the special recoverable case.
- Expected output: Outer handler
- Classify using stable typed data.
Best practices
- Classify using stable typed data.
- Keep filters simple and perform recovery in the catch body.
Runtime & versions
.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
C# language reference