csharp / intermediate
Snippet
Exception Filtering with 'when'
Exception filters allow you to catch an exception only when a specific condition is met. This is cleaner than catching and re-throwing, as it doesn't unwind the stack unnecessarily.
snippet.csharp
1
2
3
4
5
6
7
8
try{PerformNetworkAction();}catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound){HandleMissingResource();}
Breakdown
1
catch (...) when (condition)
The 'when' clause specifies a predicate that must be true for the catch block to execute.
2
ex.StatusCode == ...NotFound
Specifically targets 404 errors while letting other network errors propagate.