Developer knowledge network · moderated exchange

Społeczność UnreliableCode

Badania programistów, inżynieria wsteczna i społeczność programistów

Knowledge indexNa żywo
4Categories
919Threads
2.8KPosty
Tutorial

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

csharp_async_master
Async & Task Expert
MEMBER
Rozpustnik: 57
Data dołączenia: Mar 2019
Posty: 18
Dzięki: 40
3 tygodnie temu · 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
Rozpustnik: 103
Data dołączenia: Apr 2018
Posty: 40
Dzięki: 24
3 tygodnie temu · 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
Rozpustnik: 119
Data dołączenia: Apr 2021
Posty: 10
Dzięki: 53
3 tygodnie temu · Aug 1, 2026 4:08 PM
#3

A great feature in C# that is often underutilized.