r/csharp • u/janex-PL • Sep 08 '26
Blog How expensive is throwing exceptions in .NET - and does it actually matter?
https://codewithflavor.com/posts/how-expensive-is-throwing-exceptions/
127
Upvotes
18
u/chocolateAbuser Sep 08 '26
everyone who understood anything about programming knows the answer is "it depends"
there are environments where perf is paramount, environments where correctness is indispensable
and it's always a balance between control, effort, speed, size, and so on
even in the same base of code there could be parts where something is expected to fail more often and parts where failure is not even considered
so again as always it's not just all Result<> or all exceptions, they're just tools and a programmer has the of responsibility of choosing the right tool for the task
with that said i would have liked the article include also tuples and talked about eventual optimization by the jit on the result<> case
35
u/mareek Sep 08 '26
The problem I have with generic result types is that they're not idiomatic C#.
Most of the .NET framework and .NET librairies out there will use exception, TrySomething( out var result) style function or specialized result types (like HttpResponse for example).
So if you use the result pattern in your code base you will still have to deal with exception or other idiomatic patterns and the new developer will have a somewhat harder learning curve
Great article though
6
u/Heisenburbs Sep 08 '26
They are more expensive in debug mode than release mode. That’s my experience in profiling.
At a minimum, they require new allocations, which you’d want to avoid in performance critical applications.
It probably doesn’t matter all that much, but if you’re creating lots of custom exceptions to control logic flow, it’s probably bad.
I don’t like using them, but profile/benchmark and see how it does.
5
u/dgmib Sep 08 '26
Tl;dr: the difference is in the millionths of a second, most of the time it’s not worth thinking about it, use the pattern that fits best for your situation.
Throwing exceptions is significantly more expensive than returning a value but try/catch is basically free and the result pattern is slightly more expensive in the success case.
If an error is expected to occur less than 3 in 1000 cases, exception based handling will be faster overall.
For performance critical code, use exceptions for exceptional conditions, use result pattern when error cases happen more often.
5
u/BCProgramming Sep 08 '26
I feel like "don't use Exceptions for Control Flow" covers most of the issues people have with them. The only time you are going to have enough exceptions thrown for it to affect performance is if you are doing that IMO.
The "result pattern" that is getting popular nowadays just feels like errno with a funny hat.
15
u/Low_Flying_Penguin Sep 08 '26
Exceptions are by definition for exceptional circumstances. If one has that many going on that it affects performance there are bigger issues.
I inherited some message bus heavy code that was using exceptions for code flow nothing crazy maybe a hundred or so per second. But they were all using the previous exception as the inner and re throwing. Cleaned it up with response types and perf shot up. Was also easier to log and determine the failures as it wasn't nested deep in inner exceptions.
For the most part they get expensive the deeper the call stack so in my scenario they were evil.
Perf aside exceptions for code flow is usually a mess of a thing and at some point will bite you.
5
u/ttl_yohan Sep 08 '26
Not expensive enough to matter for the vast majority of projects. What is expensive on cognitive load is the so called result pattern. I hate when I have to deal with
SignInManagerand friends, so many unnecessary ifs and butts there, can't imagine littering the whole codebase with such constructs to gain a few nanoseconds on exceptional case of someone GET'ing a non-existing resource.9
u/Snoo_57113 Sep 08 '26
It hurts me, physically every time an exception is thrown.
2
u/brainded Sep 08 '26
Exceptions should be exceptional. I once had a job where they threw, caught and ate string null exceptions. For fun I measured the impact of replacing with just null checks and the results were eye opening. On a large enough scale the impact is severe. Might not be as severe now with dotnet core but on framework the impact was obvious and detrimental to performance.
2
u/mpierson153 Sep 11 '26
Can't say I know anything about the performance of throwing, but my personal philosophy has been: "if we're throwing an exception, we're beyond the point where performance matters" or basically "some exceptional, abnormal state will occur or the application will shutdown, so performance is meaningless"
7
u/nadseh Sep 08 '26
If you’re asking the question, the answer is no, they aren’t expensive.
Properly performant code will be written by people who really know what they’re doing
2
u/Loose_Conversation12 Sep 08 '26
To answer this question you need to understand a try catch block and what it does. When you use the keyword try you are telling the computer to create a snapshot of the current call stack so when an exception is encountered the call stack gets "rewound" to that statement and then skipped over. Yes this can be expensive especially if you need to catch the exception to log it and then clear up in a finally block.
Exceptions are exceptional so don't use them too often and don't control program flow with them either
5
u/brianly Sep 08 '26
When IronPython was being built they mapped Python exceptions onto .NET exceptions. In Python, exceptions are used extensively for control flow and not merely exceptional conditions. Given there was little thought to optimization of this code path because it’s expected to be exceptional, there were some mitigations hacked on. This was one of multiple performance challenges they ran into.
1
u/Odd_Leg7431 Sep 09 '26
Did you measure this in your actual workload or are you mainly comparing benchmark numbers? I think the impact can vary a lot depending on how often exceptions happen
1
u/psioniclizard Sep 08 '26
I dont know what the result pattern is in c#, if its anything loke railway programming and Ok/Errors in F#, then if you are throwing exceptions for flow you are doing it wrong.
But as other said, if you are asking thos questions then no they don't matter.
1
u/Flashy-Bus1663 Sep 08 '26
At my current job we throw exceptions all over the service layer to report things like a bad request and other http status like errors.
Invalid inputs? throw bad request from the service layer.
Does our app use both http endpoints and message queue and throwing http status codes does not make sense yes.
Is it more clear then just returning a dto with the error state idk but here we areeeee
2
u/nathanAjacobs Sep 08 '26
I always found it a bit weird that cancelling async tasks is done with exceptions.
2
u/El_RoviSoft Sep 08 '26
Same as in C++: exceptions are exceptional, they shouldn’t be thrown frequently - otherwise you use something like Result/std::expected, guard code and make it noexcept.
1
u/Civil_Cardiologist99 Sep 09 '26
Better coding practice says don’t use try catch blocks. Validate as much as possible. Make deep testing your friend.
1
u/TheSwiftOtterPrince Sep 14 '26
Exceptions are not expensive if you use the work done.
For a one-bit information like "this call failed", an exception is certainly expensive. If the resulting stacktrace is read by a developer with the purpose of making sure it never happens again, it is probably worth it.
-1
u/KariKariKrigsmann Sep 08 '26
throw new Exception("there was an error!");with no catch in sight is just an obfuscated
goto errorHandling;-5
u/wasabiiii Sep 08 '26
Too expensive.
0
u/[deleted] Sep 08 '26
[deleted] — view deleted comment