0 day streak
csharp / intermediate
Snippet

Selective Catching with Exception Filter Expressions

Exception filters (using the 'when' keyword) allow you to catch an exception only if a specific condition is met. This is cleaner than catching and re-throwing, and it preserves the original stack trace.

snippet.cs
csharp
1
2
3
4
5
try {
PerformNetworkAction();
} catch (IOException ex) when (ex.Message.Contains("Timeout")) {
Console.WriteLine("Retry necessary due to timeout.");
}
Breakdown
1
when (ex.Message.Contains("Timeout"))
The catch block only executes if this boolean expression returns true.
2
catch (IOException ex)
Specifies the base exception type to filter against.