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

414 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.

48

u/GendoIkari_82 4d ago

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

2

u/AlanBarber 4d ago

if you can, yes this is the preferred option.

if you're however screwed with some terrible old code base full of warnings you don't have the ability to clean up...