Developer knowledge network · moderated exchange

UnreliableCode қауымдастығы

Әзірлеушілерді зерттеу, кері инженерия және кодтау қауымдастығы

Knowledge indexТірі
4Categories
919Threads
2.8KЖазбалар
Tutorial

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

csharp_async_master
Async & Task Expert
MEMBER
Өкіл: 57
Қосылу күні: Mar 2019
Хабарламалар: 18
Рахмет: 40
3 апта бұрын · 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
Өкіл: 103
Қосылу күні: Apr 2018
Хабарламалар: 40
Рахмет: 24
3 апта бұрын · 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
Өкіл: 119
Қосылу күні: Apr 2021
Хабарламалар: 10
Рахмет: 53
3 апта бұрын · Aug 1, 2026 4:08 PM
#3

A great feature in C# that is often underutilized.