csharp / expert
Snippet
Advanced Conditional Catch Blocks for Logging Interception
Expert-level exception handling often involves 'exception filters' that execute logic before the stack is unwound. By returning 'false' from a filter method, you can perform side effects like logging while allowing the exception to propagate to a more specific catch block.
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 bool LogException(Exception ex){Console.WriteLine($"Error: {ex.Message}");return false; // Continues searching for next catch}public void ExecuteProcess(){try{throw new InvalidOperationException("Critical Failure");}catch (Exception ex) when (LogException(ex)){// This block is never reached because LogException returns false}catch (InvalidOperationException ex){// Actual handling happens here after silent logging aboveHandleError(ex);}}
Breakdown
1
when (LogException(ex))
Evaluates the expression without catching the exception if it returns false.
2
return false;
Ensures the filter doesn't claim responsibility for handling, preserving the stack trace.