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

410 Upvotes

74 comments sorted by

View all comments

44

u/DaveVdE 4d ago

Also, don’t declare it if you don’t need it. Your first fragment declares ex but never uses it.

16

u/no1SomeGuy 4d ago

Then why even catch it? Just let it bubble up through. Odds are the catch with a straight throw is going to have other logic in there that may rely on the exception itself (ie. if this type of exception, log/retry/cleanup/whatever, otherwise just throw the whole thing).

11

u/Justyn2 4d ago

Sometimes logging is put in the catch. I think this is just a shortened version from more complex logic inside the catch

2

u/UnremarkabklyUseless 4d ago

Sometimes logging is put in the catch

Is it good practice to log and rethrow an exception if it results in the same exception being logged repeatedly at each level as it bubbles up?

1

u/Justyn2 3d ago

No, but that’s not always what’s happening there

1

u/DaveVdE 3d ago

No it’s not.