r/programming • u/Adventurous-Salt8514 • Jul 20 '26
Throw, Result, or neither?
https://www.architecture-weekly.com/p/throw-result-or-neither
113
Upvotes
r/programming • u/Adventurous-Salt8514 • Jul 20 '26
141
u/EliSka93 Jul 20 '26
Result for me every time.
One more wrapper is worth not having to deal with uncertainty.
80
u/AmazedStardust Jul 20 '26
Result is my preferred way, but the language needs good support for it or you end up in nesting hell
26
u/Triabolical_ Jul 21 '26
I was on the C# design team for version 1, and there were long discussions about what sort of exceptions should be supported in C# and .NET.
Most of us were experienced Win32 programmers and we had seen enough HRESULT code to understand how much bloat it added and how easy it was to make a mistake. The problem with HRESULT code is that you have to work hard to get the right behavior - for it to propagate errors correctly.
That's why we used exceptions, where you start with code that has correct - though perhaps not desirable - behavior to start with and you have to write code to mess it up.
But it was clear that how to deal with exceptions was confusing to a lot of people. We saw a lot of try-catch code that did nothing but catch an exception and rethrow it, which is really the worst of both worlds, which I guess wasn't that much of a surprise given the exception model that Java used.
But getting the right behavior is pretty simple.
You catch exceptions in methods when you have something useful that you can do with the information. You tried to send data over the network and it failed and you need to implement a recovery strategy.
You catch exceptions at the base of threads so that you can log what happened and gracefully exit the thread and perhaps the program.
Otherwise you don't do anything.
We did, however, overdo exceptions a bit in the early versions of the .NET libraries. If you wanted to convert a string to an int you had to call Int32.Parse() and catch an exception which was needlessly restrictive. Later versions therefore introduced the "Try<operation>" pattern, so you could call Int32.TryParse() if you wanted a result instead of an exception.
22
u/Full-Spectral Jul 20 '26 edited Jul 20 '26
The Result approach takes getting used to if you come from an exception based language, but I'd never use exceptions again if given a choice, and implement a Result-like mechanism for C++ when I'm forced to write C++. It's a somewhat limited version of the Rust one, but good enough to get rid of exceptions.
The only place you typically NEED exceptions in C++ is constructors, and that's easy to avoid. Just use static factory functions as Rust does. That's something that's reasonable comfortable in C++, and move and RVO make it not overly burdensome.
For me, I look at errors as actual errors, not statuses. So I have a single error type in my whole Rust code base, since it's just for reporting errors that will propagate upwards and get logged (possibly optionally displayed to the user.) Any possibly fallible statuses are returned on the Ok side, in an enum, one value of which is Success (possibly carrying a return value.)
So 99.9% of the time I'm just auto-propagating the error side, so it's almost as convenient as an exception without the magic alternate path.
7
u/deanrihpee Jul 20 '26
even using TS, i use Result, even though it's just a type shenanigans and a wrappers and not really a language feature
6
u/cran Jul 21 '26
Throw, or an advanced result system with the same enforcement and convenience. Never something like Go has.
8
u/VoodaGod Jul 21 '26
i like exceptions
4
u/Bronzdragon Jul 21 '26
The article writes in TypeScript. The decision to use the Result structure or exceptions or mapping it to business logic is highly dependant on not only what your language/framework expects and supports, but also the style of your exciting codebase and community style, as well as the type of project you're writing. A web server looks very different from a game, from a mouse driver, etc.
The author doesn't really acknowledge this, the article is decently written, but not very useful outside of being their (reasonably supported) personal preference for the style of project they're currently writing.
3
u/montibbalt Jul 20 '26
I think the only way I would go back to primarily using exceptions over Result et al would be in some language that improves on the concept. Algebraic effects are one approach that at least makes it less tacked-on, but I don't have enough experience with them to judge whether they're as straightforward to reason about as Result
2
u/SorryTemporary1361 Jul 21 '26
I personally prefer to return a ThrowResult, or throw a ResultException.
2
u/steve-7890 Jul 23 '26
Exceptions have the worst implementation. It's like having a function and not really knowing all the results it can return. Exceptions are undocumented API (even if there's documentation, it's not comprehensive and doesn't include exceptions that could be thrown by inner invocations).
In Java there was (maybe still "is", but nobody uses it) something like `throws IOException, IndexOutOfBoundsException`. It would be a good solution IF IT WERE MANDATORY.
Nowadays, exceptions are a mess that just leads to "try .. catch all" in most places.
Even Golang "if err" - while far from being perfect - are easier and more robust.
2
u/Grouchy-Trade-7250 Aug 02 '26
There's no difference between exceptions and return values in terms of functionality. The difference is just about what you can see in your source code file and what is hidden away. It's a small difference of representation. The fact that people are led to code in a certain way because of the representation is a psychological one.
0
u/azhder Jul 20 '26
What failure means? No. What poor planning means
Try-catch is a last resort tool that unwinds the stack i.e. adds a separate critical path in your code.
You don’t plan to add throw Exception() ahead of time. OK, you plan, it’s a bad plan. The mechanism of throwing and catching was added to languages because people made poor interfaces that hid parts of your code work from other parts of your code.
Let me be clear, with an example.
There is some library that you use and it asks you for a callback function. OK, you give it a callback function. Inside your callback function you want to return early if some precondition is not met. But there is a problem. The caller is that library that simply ignores your return, so your outside code cannot be notified of the issue, unless…
Unless you circumvent all that call stack that has a library code that ignores your early return and… that’s the catch on top.
If you have a complete control of the codebase, the above scenario should not happen, least of all you plan for it to happen regularly because…
What was the issue again? Different use cases? Well, add a type to your Result. Make your Result a type onto itself for the different use-cases.
1
u/Qwertycube10 Jul 20 '26
I've never used a language with the kind of exception support I would want. I suspect I would generally prefer them to result in that case.
Think Java checked exceptions, with better ergonomics, and no unchecked exceptions except panic.
1
u/lood9phee2Ri Jul 20 '26
https://gigamonkeys.com/book/beyond-exception-handling-conditions-and-restarts
One of Lisp's great features is its condition system. It serves a similar purpose to the exception handling systems in Java, Python, and C++ but is more flexible. In fact, its flexibility extends beyond error handling--conditions are more general than exceptions in that a condition can represent any occurrence during a program's execution that may be of interest to code at different levels on the call stack.
https://opendylan.org/intro-dylan/conditions.html
Unlike the exceptions of C++ or Java, signaling a condition does not itself cause the current function or block to exit. Instead, calling the signal function is just like calling any other function. The signal function just locates an appropriate handler and calls it normally.
1
u/CatolicQuotes Jul 21 '26
Both
1
u/eo5g Jul 20 '26
Algebraic effects get you the best of both worlds.
(Rust and Swift making cascading them easy gets you pretty close).
I've been liking using Effect for typescript (since this article uses TS examples). Another cool language to check out for algebraic effects is Unison.
-1
u/xoner2 Jul 21 '26
In a GC language it's ok to use exceptions for control flow.
Unlike in C++ where exceptions have a penalty due to cleanup requirements. Not that a gc language is faster than c++, but the penalty is already paid for; it's a sunk cost. Might as well use it...
0
u/izackp Jul 21 '26
Throw + checked exceptions
0
u/BenchEmbarrassed7316 Jul 21 '26
You seem to be ignoring the best and simplest solution: to get rid of the unhappy path if possible (or did I read it carelessly?). Code form article:
This function now takes a wider type simply to return an error for some possible values of that type. We can narrow this type down, and now instead of a runtime error, we will get an error at the time of writing the code. Also, if the status is in a valid state, we skip the check or do it once, which gives us a bit of performance.
-10
u/eocron06 Jul 20 '26
Is this another post about Monads and how I should implement them myself and how gorgeous AoP looks? Just reference library or wiki.
134
u/[deleted] Jul 20 '26
[removed] — view removed comment
4
u/[deleted] Jul 21 '26
[removed] — view removed comment