csharp / expert
Snippet
Non-Unwinding Exception Filter Logic
Exception filters using the 'when' keyword allow for conditional catching. By calling a method that returns 'false', you can perform side effects like logging or auditing without actually catching the exception, preserving the original stack trace for further debugging.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
try{ProcessTransaction();}catch (Exception ex) when (AuditFailure(ex)){// Execution never enters here because AuditFailure returns false}static bool AuditFailure(Exception ex){Console.WriteLine($"Audit Log: {ex.GetType().Name} - {ex.Message}");return false; // Returning false ensures the stack remains intact for higher-level debuggers}
Breakdown
1
when (AuditFailure(ex))
The filter expression is evaluated before the stack is unwound.
2
return false;
Crucial instruction that prevents the catch block from triggering while still executing the method logic.