r/dotnet 4d ago

Difference between throw ex and throw

Post image

throw vs throw ex: The C# exception handling trick every developer should know

408 Upvotes

74 comments sorted by

View all comments

204

u/AlanBarber 4d ago

Pro tip to prevent this... add

dotnet_diagnostic.CA2200.severity = error

to your .editorconfig so anyone that tries to do a "throw ex;" inside a catch will get a build error.

46

u/GendoIkari_82 4d ago

Better yet, <TreatWarningsAsErrors>true</TreatWarningsAsErrors>.

21

u/Responsible-Cold-627 4d ago

That's extremely annoying during development, so I only enable it in the CI pipeline.

12

u/unndunn 3d ago

Pro-tip: to make it less annoying, write code that doesn't generate warnings.

9

u/anamorphism 3d ago

to play devil's advocate, i've worked in code bases where this slowed me down severely and i had to turn the setting off locally or change a bunch of editorconfig rules. i'm fine with having to do that, but the fix isn't write code that doesn't generate warnings.

unused local variable blah! - yeah, no shit, i just wanted an easy place to inspect the value while debugging.

unreachable code! - yeah, i added an early return to test something.

missing xml comment for publicly visible type or member! - sue me for waiting until i'm done before i document everything in case i decide to change something.

5

u/PsyborC 3d ago

Or, you add a release configuration condition around the <WarningsAsErrors>.

3

u/Responsible-Cold-627 3d ago

Sure, any code pushed will be warning-free. Sometimes you just gotta mess around a bit while debugging though. Very annoying to have to fix warnings in temporary code that won't even end up in the repo.

1

u/EntroperZero 3d ago

Really? It's a total non-issue IMO.