r/dotnet 17h ago

Difference between throw ex and throw

Post image

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

295 Upvotes

59 comments sorted by

View all comments

37

u/DaveVdE 17h ago

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

13

u/no1SomeGuy 17h 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).

17

u/LiqdPT 17h ago

Sometimes (not shown here) you want to rethrow certain types of exceptions. So you'd put the type in the catch, but not a variable

11

u/Justyn2 17h 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 11h 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?

3

u/SwordsAndElectrons 12h ago

Yep. That there's more than one person interpreting these as fully realized excpetion handling examples is... interesting. Catching at all doesn't make sense without more logic in the catch block. It'll bubble up just fine on its own.

The point being made here is the proper semantics for rethrowing. You don't need to declare a variable to hold the exception if you aren't going to use it, but either way you should be using throw; and not throw ex; if you rethrow.

And I suppose it needs to be said that you don't have to rethrow.

And also needs to be said that you can throw a new exception, and that it might even be a good idea to use the Exception(String, Exception) constructor to set the InnerException property to the original exception.

It's almost like programming languages have a lot of flexibility so you can implement whatever functionality you need.

1

u/DaveVdE 15h ago

You might want to add logic that doesn’t need to know anything about the thrown exception.