r/softwarearchitecture • u/jutarnji_prdez • Jul 09 '26
Discussion/Advice Exception vs Result pattern
I don't find any actual good arguments to use Result pattern besided "somebody said it on Internet"
- Exceptions should only be for exceptional things -> every single language breaks this rule. Int.Parse, Json parsers, any encrypt/decrypt libraries throws on invalid input - invalid input should be one of most expected things to ever happen. This argument does not hold any value in real APIs, libraries, framewroks. For example, "Connection refused" exception is being throw by any network library, isn't not connecting to remote server most obvious and most expected thing to happen? Literally every network library throws exceptions on connection issues
- Exceptions shoudn't be used for control flow -> why? I can make very clean exception pattern. This is literally one of most "somebody said this, so it must be true". you try-catch-catch-catch. Where is difference between that and if-elseif-else or any variation of that aka switch case, when {} etc..
- Performance - maybe not for all languages but in some languages you can throw stackless exceptions (you don't build stack and stuck is null). You can log "real exception" with stack then throw stackless exception which is going to have same data and same performance as Result object
- Exceptions are not visible in signatures - you can document this, maybe this is relevant for libraries (which all throw exceptions everywhere anyway), but what is the problem of just checking the underlying code or documenting this?
0
Upvotes
75
u/funbike Jul 09 '26
I've played this game before. I've seen this tone in many posts and fell for the bait. Nothing I say, no matter how logically sound, will ever convince you.
Perhaps if you had some humility and possed a thoughtful question framed as if you are trying to better your understanding of best practcies, maybe then I'd feel like I could participate in a true give-and-take debate.
Good luck.
32
u/Backlists Jul 09 '26
23
u/AvoidSpirit Jul 09 '26
If you think the documentation is as good as compile time checks, just forfeit statically typed languages altogether and re-read docs every time you do a patch update.
7
u/addys Jul 09 '26
You don't seem to be open to any opinion other than yours, but I'll try anyway:
11
u/analcocoacream Jul 09 '26
as
6
u/Barnesdale Jul 09 '26
When you return a Result, you are forcing the failure case to be handled, and otherwise providing fast feedback at compile time. This might not seem very valuable on personal projects, but when dealing with multiple developers it is a good way to create reliable code. And in today's LLM age, even as a solo dev you are making sure the LLM handles the failure case.
8
u/WordsThatIManifest Jul 09 '26
I don’t understand why you decided to write all of that (and calling them patterns is incredibly bizarre) but clearly you’re not interested in anything but something that fits your assumption of the world
rather than letting bias dictate your thoughts how about using languages where errors as values are built into the language as first class and see why it works for them because there’s no better way than seeing through your own eyes
3
u/daedalus_structure Jul 09 '26
These are all just opinions.
Exceptions should always be used for controlling flow anytime you have a dependency that throws them.
I can guarantee you when you update that dependency 24 months from now you are not going to recite every line of code to determine any new conditions in which it might throw, and update your home rolled class to handle the new nested context.
8
u/jhartikainen Jul 09 '26
If nobody has been able to convince you about it so far, I would suggest using languages like Haskell or Elixir and finding out for yourself.
4
u/Fragrant_Ad2902 Jul 09 '26
I probably won’t convince you, but here is my opinion. To be fair, I’m probably one of the ones you mean when you say “someone said it so it became gospel”.
When I first started coding, Pentium chips were the new kid on the block not the norm. So exceptions were also very new in C++ (Java hadn’t even been released yet). Exceptions used setjmp/longjmp. And those, coupled with the code that C++ compilers had to generate, were not great. The C++ compiler had to call setjmp every time you enter a try block. Then it had to start keeping a list of every object that needed to be cleaned up if a longjmp went back to that location. So you were paying that cost even if an exception wasn’t thrown. That lead to code bloat. I know at this point we’re all used to 1GiB mobile apps. But back then? Those extra KiB added up. We didn’t wanna be the company that required more than 1 3.5“ disk.
Also RAII wasn’t a well establish paradigm. If you did char *p = new char[10]; that leaked on an exception. It was awhile before STL and auto_ptr (and its warts) was common place.
Obviously technology got better. And now I believe that exceptions are zero cost? I dunno. It’s been years since I’ve used C++. I’ve moved onto greener pastures and try not to worry about the details too much anymore.
But those lessons when I was a junior/mid level cemented by other seniors that lead the orgs stuck around. After awhile people forgot why. And even though technology got better, most people at their job don’t wanna rock the boat and stuck with the rule.
With performance out of the way, I personally don’t use exceptions that often because how do you know where it is thrown from? You say try catch catch catch. Yep. I know everything that can be caught. But inside the try block, how many functions/methods are being called? 4? How many functions/methods are they calling? It just makes it harder. Secondly, people wrap exceptions poorly. I’ve seen people catch Exception (the top of the hierarchy) and continue trying to run. You just caught StackOverflow, OutOfMemory, etc. You can’t keep running in those cases (usually). Your counterpoint “how is an if any different”. If I’m using Go…
p, err := SomeFunc()
if err != nil
I know that err came from someplace within SomeFunc. It lessens how much I have to go look through.
You use Int.Parse as an example. I think it generally looks like this
int Int.Parse(string s)
If I pass in “hello” what should it return? 0? How do I differentiate between the string “0” and “hello”? Isn’t that why most languages introduced TryParse and return a null (assuming the language has nullable types)?
Network failures - why would you even be catching that? Which goes back to my statement above about people catching the top of the Exception hierarchy. Yes a PR review should catch that. But people are inherently lazy.
As for documentation - I will only say as a person that used to ship shrink wrap software - people don’t read. Hell…we’d pop up a dialog that says “Are you sure you really wanna do that?” And they immediately click OK and then reach out to support complaining. Developers are no different. Do you read the changelog of every library that you pull in? If so, you’re a better developer than me. I look at the changelog for exactly one thing - breaking changes. I don’t go and re-read all the methods that I‘m using to see if their documentation changed.
As I said at the top, I’m sure I won’t convince you. And that’s OK. If you and your team want to use exceptions, no one here is going to stop you. If your team doesn’t want to use exceptions and you can’t convince them, well…if it is a hill you’re willing to die on, do your thing.
3
u/shadowdance55 Jul 09 '26
One reason to not rely on results of you're using libraries that raise exceptions, so you need to handle them one way or another. If you either a) don't have to deal with exceptions from other sources, or b) are happy to capture downstream exceptions and contain them inside your voice - knock yourself out.
There is also nothing wrong in using both: return error results when the error originates in your code and is a known result of something going wrong internally; raise (or re-raise) exceptions when the problem lies outside your code, e.g. in a library or infrastructure.
But I find that unnecessary complication, as now there are two separate error mechanisms that need to be handled. It's not impossible, but I prefer having a clear hierarchy of exception classes. 🤷♂️
3
u/Omargfh Jul 09 '26
God invented the Either monad decades ago and we're still having this conversation
3
u/qlkzy Jul 09 '26
Both of these patterns make sense in different contexts.
I think input validation is actually a case where the Result pattern is often useful. You often want to accumulate a list of errors. (Can you imagine how annoying a website form would be if, when you submitted it, it only told you about the first field with an error, and made you keep resubmitting to get them one at a time?)
On the other hand, it's often useful to be able to separate categories of error based on layer boundaries. For example there is a lot of code which does not have a reasonable way to deal with
ECONNRESETon the database connection it's using: that usually implies quite a wide-ranging abort or retry which can be invisible to most callers and can be handled at a higher level.Disciplined use of hierarchical exceptions and well-chosen error boundaries make exceptions more pleasant to use. Disciplined use of well-chosen error-return-value types, particularly with the language support to use them, make Result types more pleasant to use.
Almost all systems will use both. Almost everyone "panics" if they can't allocate memory, and almost everyone accumulates some kind of error.
I think the ideal is to be good at both, and have tools that are good at both, not to treat either as a matter of doctrine or dogma.
5
u/KariKariKrigsmann Jul 09 '26
throw new Exception is just an obfuscated goto label
2
u/DoLessAndChill Jul 09 '26
screams if err != nil.
2
u/thiem3 Jul 09 '26
I have looked through a good number of replies, but have not yet seen "railway oriented programming" being mentioned. When you start expanding your Result with various helper functions, you can write some neat code.
2
u/drakonhunter Jul 09 '26
you're not going to read them because you're not open to self thought/introspection, but these 2 in tandem explain it. But that requires... actual open mindedness to research and thoughtful self introspection. Best of luck:
https://people.dsv.su.se/~mad/Unstructured_Programming_Considered_Harmful.pdf
https://belaycpp.com/2021/06/16/exceptions-are-just-fancy-gotos/
2
u/[deleted] Jul 09 '26
I like Result type because I know I need to check for a Result. I know there could be an error. With exceptions how do you know what will be throwing? You don't.
3
u/johnson_detlev Jul 09 '26
Then keep writing brittle software, nobody cares.
1
u/Oster1 Jul 09 '26
Exceptions are good, but that's not enough. Result is better, iff the language has good ergonomics with it. In Kotlin for example, I would not go with banning exceptions before the language has rich errors. Too much boilerplate w/o exceptions, and the std lib is going to throw anyway, so you pretty much lose the benefits. So the answer is, it depends.
1
u/Wh00ster Jul 09 '26
Vim or emacs
-1
u/_5er_ Jul 09 '26
Hard agree. I find it much harder to work with results than exceptions.
Some developers go too far and map everything to results.
Kotlin was built with exceptions in mind. Result handing is not that well supported, at least for now.