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.