csharp / expert
Snippet
Stack-Preserving Exception Filters
Expert error handling uses 'when' clauses. Unlike a standard catch block, the filter is evaluated before the stack unwinds. This preserves the full call stack for debuggers and allows selective handling based on runtime state without losing context.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void ProcessData(string path){try{File.ReadAllText(path);}catch (IOException ex) when (IsTransient(ex)){// Filter 'when' prevents stack unwinding if the condition is falseLogAndRetry(ex);}}private bool IsTransient(IOException ex) =>(uint)ex.HResult == 0x80070020; // Sharing violation
Breakdown
1
when (IsTransient(ex))
A boolean expression that must be true for the catch block to execute.
2
(uint)ex.HResult == 0x80070020
Checks for a specific underlying OS error code before accepting the exception.