Developer knowledge network · moderated exchange

Zajednica UnreliableCode

Zajednica za istraživanje, obrnuti inženjering i programiranje programera

Knowledge indexŽivjeti
4Categories
919Threads
2.8KPostovi
Tutorial

Why Exception Filters (catch when) are superior to catch-and-rethrow in C# [StackOverflow Architecture Guide]

csharp_async_master
Async & Task Expert
MEMBER
Rep: 57
Datum pridruživanja: Mar 2019
Postovi: 18
Hvala: 40
3 prije tjedana · Aug 1, 2026 7:08 AM
#1

The crucial difference between catch when and catch { if (...) throw; }:

When you use throw; inside a catch block, the stack frame has already been unwound up to that point, altering the original call stack.

Exception Filter:

CSHARP
try
{
    await ExecuteRemoteCallAsync();
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.ServiceUnavailable)
{
    // Handles only 503 without unwinding if exception is 404/500!
}

Exception filters evaluate the condition before the stack unwinds, preserving the pristine crash dump and stack trace in crash reports!

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Rep: 103
Datum pridruživanja: Apr 2018
Postovi: 40
Hvala: 24
3 prije tjedana · Aug 1, 2026 10:51 AM
#2

Exception filters also avoid unnecessary stack unwinding performance penalties if the condition evaluates to false.

sanitizer_sam
UB Hunter
MEMBER
Rep: 119
Datum pridruživanja: Apr 2021
Postovi: 10
Hvala: 53
3 prije tjedana · Aug 1, 2026 4:08 PM
#3

A great feature in C# that is often underutilized.