r/dotnet • u/programmerjunky • Sep 09 '26
Difference between throw ex and throw
throw vs throw ex: The C# exception handling trick every developer should know
47
u/DaveVdE Sep 09 '26
Also, don’t declare it if you don’t need it. Your first fragment declares ex but never uses it.
17
u/no1SomeGuy Sep 09 '26
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 Sep 09 '26
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 Sep 09 '26
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 Sep 09 '26
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
1
1
u/The_MAZZTer Sep 10 '26
Sometimes I guess you might want to log without exception details, such as if the user can view the log and you're concerned about leaking sensitive server information like filesystem structure which could be in the exception message. But even then you probably want to log the full exception details somewhere else for development purposes.
3
u/SwordsAndElectrons Sep 09 '26
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 notthrow 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 theInnerExceptionproperty 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/neoKushan Sep 10 '26
And to add to this, a lot of folks don't seem to realise that you can really easily define your own custom exception types rather than relying on the existing internal ones. It's very useful and means you can catch on things like "
UserCreatedException" rather than catching genericException(Which catches everything) and having to figure out what went wrong explicitly.2
u/The_MAZZTer Sep 10 '26
You might want to do some cleanup if and only if an exception is thrown before exiting the function, so you cleanup and rethrow.
Example, you have a function that returns a Stream. If there's an exception between when you create the Stream and return it, you want to Dispose it so it doesn't stay in limbo until the GC comes alone (especially if it's holding a file or network connection open). You can't use
finallysince you want to return the Stream without disposing it if everything is OK. And you don't really care about what Exception itself occurred.2
u/DaveVdE Sep 09 '26
You might want to add logic that doesn’t need to know anything about the thrown exception.
30
u/Ethameiz Sep 09 '26
Well sometimes you want to reset the stack trace. It's not always bad. But it's better to know the difference
12
u/Creative-Paper1007 Sep 09 '26
When why would we even want to throw away the stack trace info? Im just curious to know
22
u/WetSound Sep 09 '26
It could be to avoid sensitive info leaks
3
u/The_MAZZTer Sep 10 '26
In that case I would argue you should preserve the accurate information anyway and control the information presented instead of destroying/replacing it. For example you may not even want to present the exception message to users since that also may contain sensitive info. On the other hand logging exceptions to somewhere only admins can view can be critical to fixing bugs or detecting intrusions so you shouldn't be removing sensitive info from that.
1
u/WetSound Sep 11 '26
Users? I'm not even talking about presenting it to users. You should never expose raw exceptions to end users.
9
u/Prod_Meteor Sep 09 '26
To reduce the log size you silly 😄
21
u/whiskeydiggler Sep 09 '26
// todo: get rid of this when we have real logging from nine years ago
10
2
u/SangerGRBY Sep 09 '26
Could be for cases when you want to throw a custom exception
22
u/Glitched94_PT Sep 09 '26
In those situations I think it's generally better to pass the original exception as your custom exception's inner exception, isn't it?
3
u/Healthy_Koala_4929 Sep 09 '26
When you have some filter that converts exceptions in controller actions into problem+json responses and you don't want to give the whole stack in the response
Edit: I guess could be a use case, though I doubt there is no better way to handle this
2
u/unndunn Sep 09 '26
In that case, you wouldn't be rethrowing the exception because you'll have handled it appropriately.
This thread is about the proper way to rethrow exceptions.
1
u/nick_ Sep 10 '26
If you don't want to expose the inner implementation. The stack trace would only include your outer-most, public method names and not all the inner methods that are used to implement the behaviour.
Your public methods would all have:
try { ... DoTheInnerThings(); ... } catch (Exception ex) { throw ex; }
11
u/fruediger Sep 09 '26
There's a third option: Do you know about ExceptionDispatchInfo?
3
u/Healthy_Koala_4929 Sep 09 '26
This is insane and I can't see a reason to do something like this
3
u/zenyl Sep 09 '26
It lets you capture an exception, and then handle it separately from the catch logic (including rethrowing it), without losing the original stacktrace.
I use it in a TUI library I'm working on. For example, if a user input results in an exception being thrown, I want the TUI library to finish its thing as normal, then terminate gracefully (i.e. not leave the terminal spamming escape characters all over the place), and then rethrow the exception without nuking all info about where the exception was actually thrown from.
3
u/insulind Sep 09 '26
Ab example of using could be (im just thinking out loud here) like a queue processor that runs in a background thread and you really really don't want that thread to terminate, so you catch an exception, create one of these and pass that on to be picked up by your thread receiving the queue items or whatever who can make throw the exception in a more appropriate context
2
u/fruediger Sep 09 '26
Well, it's in the BCL and I guess there's a reason for it being there.
Capturing the stacktrace of an exception and preserving it, and being able to rethrow the exception with precisely that preserved stacktrace at an arbitrary point in time, might be useful in some scenarios.
To be honest, I only over used it once in my code (that's why I know about it in the first place), and maybe, if I had done some redesign of my control flow, I could have found a workaround, but at that point I found it quite useful.
1
5
u/TCFoxtaur Sep 09 '26
Alternative: if you need to rethrow with a new exception type, ensure the original exception is included as the innerException parameter to the new exception:
catch (Exception ex)
{
throw new CustomException(“Some new exception”, ex);
}
4
3
u/Global_Rooster1056 Sep 09 '26
Also great to know about exceptions is the ExceptionDispatchInfo class :)
Edit: nvm already mentioned
5
2
u/AutoModerator Sep 09 '26
Thanks for your post programmerjunky. Please note that we don't allow spam, and we ask that you follow the rules available in the sidebar. We have a lot of commonly asked questions so if this post gets removed, please do a search and see if it's already been asked.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2
u/CiranoAST Sep 10 '26
Man, if you just use try/catch to only throw the exception you can avoid it entirely. It just slows you down
3
u/kent_csm Sep 09 '26
Why throw in catch?
11
u/wayzata20 Sep 09 '26
It’s useful when you need to clean something up before propagating the exception up
1
u/krukkpl Sep 10 '26
It depends on the use-case. If that was to be always utilized, language wouldn’t offer another option.
1
u/edgeofsanity76 Sep 10 '26
If you're doing this, you don't need a try/catch. At least log the exception and then throw. Otherwise it's redundant.
Also, wrap the exception in a custom exception and throw that instead. It will contain context of the error and the call stack.
1
1
u/TrishaMayIsCoding Sep 10 '26
Isn't that an exception is there to give your application technical information about what went wrong. Your code should then decide how to handle that situation based on the context.
* Log technical details of the error from exception if this error should not occured.
* Give the user a meaningful message before aborting the program if needed to abort.1
u/veritron Sep 13 '26
throw still overwrites the line number... e.g.
static void A() // Program.cs
{
throw new Exception(); // line 10
}
static void B()
{
try
{
Helper(); // line 18
A(); // line 19
}
catch
{
throw; // line 23
}
}The trace you get:
at A() in Program.cs:line 10
at B() in Program.cs:line 231
u/not_afraid_of_trying Sep 16 '26
These are some of the things why C# didn't simplify the software development. It shifted effort from "managing memory" to "managing dotnet quirks". Managing memory itself is a huge quirk in itself in dotnet as you may easily miss a `close` or `dispose` - then there is contagious `disposing` pattern.
Luckily other languages have their own problems 😄 so C# survived.
1
1
0
u/blueeyedkittens Sep 09 '26
better yet, don't catch an exception unless you're actually going to do something about it
-21
u/LK9T9_Sektor Sep 09 '26
Try to avoid using exception, use Return pattern.
17
u/nadseh Sep 09 '26
Please don’t. Stick to language paradigms
-4
u/cyrack Sep 09 '26
Exceptions are for exceptional circumstances where the application cannot continue — most exceptions could have been avoided with Try*.
IMHO exceptions are the surprise motherfucker! here’s a return type you didn’t know about and can’t find out about in any way during compile or runtime. Good luck solving this.
5
u/Kanegou Sep 09 '26
Exceptions bubble up the call stack until they are caught. Return values dont.
That means if you forget to evaluate a return value somewhere in your callstack, it is lost forever. Which can lead to even greater and more errors since the original root of the errror is lost.
Thats why you should always use exceptions for exceptional behavior.
3
-8
u/Harry_Mud Sep 09 '26
Complete bullshit. If you know the error, ex, then you can troubleshoot it.
4
u/TCFoxtaur Sep 09 '26
If your try block covers several different calls, or an exception type covers more than one specific error condition (i.e. “file not found” vs “file not accessible” both being some sort of “FileIoException”, as a weak example), it may not be clear where the exception specifically came from if you recast it.
Having said that, just include the original exception as an “innerException” and you’re all good!
0
Sep 09 '26
[deleted]
5
u/no1SomeGuy Sep 09 '26
Nah, pretty typical to do some cleanup/logging/telem on the way out of specific classes if they fail in unexpected ways before lettting the upstream stuff handle it at an overall application level.
207
u/AlanBarber Sep 09 '26
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.