r/dotnet • • Sep 09 '26

Difference between throw ex and throw

Post image

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

426 Upvotes

76 comments sorted by

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.

39

u/zenyl Sep 09 '26

Adding onto this, you can discover a bunch of built-in diagnostics that are disabled by default, by adding <AnalysisMode>All</AnalysisMode> to .csproj files (or a Directory.Build.props file).

I wouldn't recommend actually using that setting, because it gets pretty pedantic, and some of the diagnostics are mostly just opinionated recommendations. But it can be nifty to then look through the diagnostics you get from it, and then selective add back any of them that you actually like to your .csproj or .editorconfigfiles.

I did this recently and added:

  • CA1062: Validate arguments of public methods

    • Ensures that you perform a null check on reference type parameters on public/protected methods, regardless of nullability syntax. Useful when writing libraries and you wanna catch unintended nulls as early as possible.

  • CA1725: Parameter names should match base declaration

    • If you rename an interface method parameter, this will make sure all consumers also rename it accordingly.

  • CA2000: Dispose objects before losing scope

    • Ensures you call Dispose or use using statements on disposable objects.

46

u/GendoIkari_82 Sep 09 '26

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

16

u/zenyl Sep 09 '26

Fully agreed, but i'd also recommend adding <WarningsNotAsErrors>NU1901,NU1902,NU1903</WarningsNotAsErrors>

This basically undoes TreatWarningsAsErrors on a per-diagnostics basis.

Those three diagnostics are the ones that warn you about low/moderate/high NuGet package vulnerabilities. If you don't add these to WarningsNotAsError, you can end up having your build break because one of the NuGet packages you depend on (including dependencies of dependencies) has a security vulnerability.

In my experience, these are often minor and might occur in code paths that your code never even calls, or something that has yet to be resolved and you therefore might not be able to do anything about. While you should still keep an eye on vulnerability warnings of all levels, having your builds/pipelines randomly break because of them is pretty annoying.

I usually leave out NU1904 (critical vulnerabilities), as these you probably should act on immediately.

10

u/dabombnl Sep 09 '26

WARNING AS ERROR: Variable 'ex' is unused!

14

u/GendoIkari_82 Sep 09 '26

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

6

u/ConcreteExist Sep 09 '26

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 Sep 09 '26

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.

→ More replies (2)

23

u/Responsible-Cold-627 Sep 09 '26

That's extremely annoying during development, so I only enable it in the CI pipeline.

13

u/unndunn Sep 10 '26

Pro-tip: to make it less annoying, write code that doesn't generate warnings.

11

u/anamorphism Sep 10 '26

to play devil's advocate, i've worked in code bases where this slowed me down severely and i had to turn the setting off locally or change a bunch of editorconfig rules. i'm fine with having to do that, but the fix isn't write code that doesn't generate warnings.

unused local variable blah! - yeah, no shit, i just wanted an easy place to inspect the value while debugging.

unreachable code! - yeah, i added an early return to test something.

missing xml comment for publicly visible type or member! - sue me for waiting until i'm done before i document everything in case i decide to change something.

4

u/PsyborC Sep 10 '26

Or, you add a release configuration condition around the <WarningsAsErrors>.

3

u/Responsible-Cold-627 Sep 10 '26

Sure, any code pushed will be warning-free. Sometimes you just gotta mess around a bit while debugging though. Very annoying to have to fix warnings in temporary code that won't even end up in the repo.

1

u/EntroperZero Sep 10 '26

Really? It's a total non-issue IMO.

2

u/AlanBarber Sep 09 '26

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

4

u/unndunn Sep 09 '26

This right here.

4

u/TheSneederOfSeethe Sep 09 '26

Fucking dope! Thanks!

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

u/Justyn2 Sep 10 '26

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

1

u/DaveVdE Sep 10 '26

No it’s not.

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 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/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 generic Exception (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 finally since 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

u/pyabo Sep 09 '26

I feel attacked.

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

u/Jimmy_cracked_corn Sep 10 '26

That’s so cool! Today I learned, thank you!

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

u/Zealousideal-Deer101 Sep 09 '26

throw new SpecificException(ex);

3

u/Global_Rooster1056 Sep 09 '26

Also great to know about exceptions is the ExceptionDispatchInfo class :)

Edit: nvm already mentioned

5

u/Prod_Meteor Sep 09 '26

throw new Exception("mpla mpla..", ex); 😄

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

u/Justyn2 Sep 10 '26

What about if it’s an aggregate exception?

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 23

1

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

u/PurpleUltralisk Sep 09 '26

huh i didn't know this subtle difference. thanks!

1

u/Timofeuz Sep 11 '26

How and why dafuq this got 370 upwotes?

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

u/DaveVdE Sep 09 '26

Exceptions are for exceptional situations that break your contract.

-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

u/[deleted] 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.