csharp / expert
Snippet
Strategic Exception Filtering with Contextual Guards
Expert-level error handling in C# utilizes the 'when' keyword to filter exceptions without unwinding the stack. This is more efficient than catching and re-throwing because it preserves the original stack trace and allows for complex logic to determine if a catch block should execute.
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
23
public class ResilienceHandler{public static void ExecuteWithRetry(Action action, int maxRetries){int attempts = 0;while (true){try{action();break;}catch (Exception ex) when (attempts < maxRetries && IsTransient(ex)){attempts++;Console.WriteLine($"Transient error detected. Retry {attempts}/{maxRetries}.");}}}private static bool IsTransient(Exception ex) =>ex is TimeoutException || (ex is InvalidOperationException ioe && ioe.Message.Contains("Retryable"));}
Breakdown
1
catch (Exception ex) when (attempts < maxRetries && IsTransient(ex))
Applies a conditional filter that only catches the exception if the retry limit isn't reached and the error is transient.
2
private static bool IsTransient(Exception ex) => ...
Encapsulates complex logic to identify recoverable errors based on type and internal state.