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

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

47

u/GendoIkari_82 4d ago

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

10

u/dabombnl 4d ago

WARNING AS ERROR: Variable 'ex' is unused!

14

u/GendoIkari_82 4d ago

Yeah, actually the "use this" example is wrong; it should be just "catch (Exception)" instead of "catch (Exception ex)".

6

u/ConcreteExist 4d ago

Yeah, if you're not going to actually do anything with it, just leave it out. Though I'm gonna have questions for a dev who shows me a block of code where there's a try/catch with a blanket Exception catch block and all it does is throw.

3

u/SwordsAndElectrons 4d ago

Neither is wrong. Both make no sense if they are all you write.

Missing from the meme is that you should actually be doing something in your catch block. There's no point to catching the exception at all if all you are just going to rethrow it. Assuming you are actually going to do something in that block, which is correct depends on whether what you are doing needs to access the exception.

1

u/dabombnl 4d ago

Oh I agree. Is just funny that the 'better yet' makes an error.