csharp / expert
Snippet
Conditional Exception Filtering
Exception filters (the 'when' clause) are superior to catching and re-throwing because they allow the runtime to decide whether to enter a catch block before the stack is unwound. This is critical for post-mortem debugging (e.g., memory dumps), as the stack trace remains intact at the point of failure. If the filter returns false, the exception continues to propagate as if it were never caught.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class GlobalErrorHandler{public static void ProcessData(Action action){try{action();}catch (Exception ex) when (LogAndContinue(ex)){// This block is never reached because LogAndContinue returns false}}private static bool LogAndContinue(Exception ex){Console.WriteLine($"Logging error: {ex.Message}");// Returning false tells the CLR to keep searching for a catch block// without unwinding the stack yet.return false;}}
Breakdown
1
catch (Exception ex) when (LogAndContinue(ex))
Executes the filter method to decide if this catch block should handle the exception.
2
return false;
By returning false, we log the error but allow the exception to bubble up, preserving the original stack context.