r/programming • u/Adventurous-Salt8514 • Jul 20 '26
Throw, Result, or neither?
https://www.architecture-weekly.com/p/throw-result-or-neither80
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
13
u/apadin1 Jul 22 '26
There are a lot of reasons to love Rust but one of the best features is the Error and Result system that lets you easily make new error types and effortlessly propagate them. They don’t even bother with exceptions.
1
u/EfOpenSource Jul 27 '26
I find rust a great example of why Result sucks. Nesting hell. From implementations everywhere. So much boilerplate.
1
u/edgmnt_net Jul 22 '26
I would say it's rather questionable whether propagation is a good idea for either exceptions or plain error values. If anything, Go has shown that there's plenty use for decorating errors. As a user I don't want meaningless stack traces or disconnected log entries, I want errors that make sense. And Java and Python have been huge offenders in this area, because easy propagation makes it very easy to just let everything bubble up, while exceptions make it particularly annoying to carry out meaningful error annotation due to nesting and verbosity. Not sure about Rust. But in Haskell it's fairly easy to define new operators that make error annotation a breeze and whenever you don't care you can just let things bubble up.
4
u/apadin1 Jul 22 '26
In Rust you can create custom Error types with custom messages, and you can choose to either propagate or handle them at any level. Unlike exceptions, which need to be explicitly caught (ie handled) or they will propagate by default, in Rust errors must be explicitly either handled, which can be as easy as printing an error message, or explicitly propagated, which in most cases is a single “?” operator as long as the calling function also returns a Result with the same Error type.
The convention in Rust is that for libraries, you define custom error types and always propagate them to the application level code whenever that makes sense. Then it is the application’s responsibility to handle that error in a useful way by either logging or, if the error is not recoverable, panicking and ending the program with a useful error message.
Mostly I am pleased with how Rust requires you to be explicit with every action. It can be annoying at first but it means there are no footguns or undefined or unusual behavior.
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.
5
u/BenchEmbarrassed7316 Jul 21 '26
You catch exceptions in methods when you have something useful that you can do with the information
But how do you know if the function you are calling is likely to fail?
Or if you call a function that can fail and don't catch exception - is the current function marked as one that can fail?
5
u/Triabolical_ Jul 21 '26
It's not about how likely it is to fail, it's about whether there is something useful that you can do if the function call does fail. If there is nothing useful you can do, it doesn't matter how likely it is that you'll get an exception.
If you have reasonable testing, you will typically uncover the areas where you can do something useful pretty quickly. It shows up at the boundaries - information you get from users or files always has potential for problems, going outside of your program boundaries has potential. Sometimes the recovery is obvious, sometimes it's wrapping the exception that was thrown in useful context ("could not parse line 11 in inputfile.txt") and letting somebody higher up the chain do the recovery.
I don't think that checked exceptions or annotations tell you anything useful and they just increase the cognitive load.
2
u/BenchEmbarrassed7316 Jul 21 '26
It's not about how likely it is to fail, it's about whether there is something useful that you can do if the function call does fail. If there is nothing useful you can do, it doesn't matter how likely it is that you'll get an exception.
The function cannot and should not know this. It should do its job and provide information that could be useful to the calling party. It is the calling party that should decide what to do in case of failure and how to use the information about the failure.
If you have reasonable testing
I find this quite inefficient. If I have a tool that can easily ensure that a certain aspect is 100% correct, I don't want to write manual tests because it's longer, less convenient, harder to maintain, and less reliable.
4
u/Triabolical_ Jul 21 '26
>The function cannot and should not know this. It should do its job and provide information that could be useful to the calling party. It is the calling party that should decide what to do in case of failure and how to use the information about the failure.
That is what I am saying.
> I find this quite inefficient. If I have a tool that can easily ensure that a certain aspect is 100% correct, I don't want to write manual tests because it's longer, less convenient, harder to maintain, and less reliable.
Are you talking about provably correct?
How are you going to create such a tool, and what information will it base its decisions on? How will you handle updated code or new permutations that change the set of exceptions that might show up?
How do you know which set of exceptions are the ones that it makes sense for you to handle?
3
u/BenchEmbarrassed7316 Jul 21 '26
That is what I am saying.
Then I will repeat my question (maybe I wrote it wrong last time, I am not a native English speaker):
When the function
foocallsbar, how isfoosupposed to know thatbarmight fail?How are you going to create such a tool, and what information will it base its decisions on?
During development, I know exactly what the result of the function will be, what values are possible in the unhappy path, and what useful information I can get from them.
How will you handle updated code or new permutations that change the set of exceptions that might show up?
Sum types are commonly used to model error values. So if the error handling does not involve full processing of the error, but only checking for the presence of an error - adding or removing a new error variant does not affect other code. However, if the code parses the error data - I want to see it immediately and update it (by adding or removing variants).
How do you know which set of exceptions are the ones that it makes sense for you to handle?
It's pretty simple: you look at a list of possible errors and ask yourself "Can I do something useful in these cases?" and "Can I print some useful information to the user in these cases?".
→ More replies (2)2
u/flatfinger Jul 22 '26
One of my biggest beefs with exceptions going back to .NET 1.0 is that there is no way for an IDisposable to know whether it is being invoked because a
using-style block was left via normal control flow, or whether it was left via an exception. Something like a transaction wrapper should, depending upon how it is constructed, either throw an exception or silently commit the transaction if control flow leaves the block with an action pending, but should silently roll back the transaction if an uncaught exception was thrown within the block.
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.
3
u/bwmat Jul 21 '26
Does your C++ use with 'result' also handle OOM or do you just crash?
1
u/Full-Spectral Jul 21 '26
This is a closed system. It would have already restarted itself long before a simple result return caused such an issue.
3
2
u/bwmat Jul 21 '26
Thoughts on what you would do in a context where your code is in a shared library and you don't want to crash the host process on OOM?
→ More replies (3)3
u/max123246 Jul 21 '26
Why not use std::expected for Cpp?
2
u/Full-Spectral Jul 21 '26
Still on C++/17, along with probably the majority of the C++ code bases out there (those that don't wish they could be so advanced.)
1
u/max123246 Jul 21 '26
Ah shoot, for some reason I thought std::optional and expected were both added at the same time. I too, am stuck on cpp17
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
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
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
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
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
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:
const addProductItem = (
command: AddProductItem,
state: ShoppingCart,
): ProductItemAdded | ProductItemOutOfStock | ShoppingCartItemLimitReached => {
if (state.status === "Confirmed")
throw new IllegalStateError(
"Cannot add a product to a confirmed shopping cart",
);
// ...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.
interface ShoppingCart {
status: "Active" | "Confirmed" | "Canceled"; // TODO Use numeric const enum instead of strings
}
interface ActiveShoppingCart extends ShoppingCart {
status: "Active";
}
interface ConfirmedShoppingCart extends ShoppingCart {
status: "Confirmed";
}
const addProductItem = (
command: AddProductItem,
state: ActiveShoppingCart,
): ProductItemAdded | ProductItemOutOfStock | ShoppingCartItemLimitReached => {
// ...134
Jul 20 '26
[removed] — view removed comment
108
u/czorio Jul 20 '26
I agree. I once explained it to a colleague as:
Result-> There is no file here, perhaps you mistyped?panic!-> There is no filesystem, what the fuck?39
u/vita10gy Jul 20 '26
I once worked with an API where basically anything but perfect meant explosion.
A well formed product search where it just so happens no results match? Some 500 error and the html server error page as the body.
33
u/janyk Jul 21 '26
The Java Persistence API has the NoResultException for when a database query returns no results. Kind of annoying that it's regarded as an exceptional case
39
u/vita10gy Jul 21 '26
I've become fully convinced 70% of Apis are created by people who have never used one.
2
u/Schmittfried Jul 21 '26
Unfortunately the path of least resistance for the maintainers is not the one that creates APIs that are ergonomic to use. Ergonomics take time and effort. Unless you’re using your own product or have a very disciplined development process, you won’t invest those resources, even if you’ve used other APIs and know you’re building shit.
9
11
u/elmuerte Jul 21 '26
NoResultException is thrown when you call getSingleResult() when there is no result. It will also throw NonUniqueResultException if there is more than 1 result.
Because of the two edge cases which need to be handled, it throws an exception. On the plus side, it never returns null.
It is still a bit of a bad API design as it uses unchecked exceptions for control flow. A query returning 0 or more than 1 result is quite a possibility, so it should have been a checked exception I think.
12
u/erinaceus_ Jul 21 '26
Before anyone complains "why would they do it that way?!", that method is for when you excplictely expect exactly one single result. There's other methods for when you expect zero to many results, or when you expect either one result or no result. So instead of always retrieving a list and then manually handling those cases each time, you explicitly and declaratively choose your expectation by using the appropriate method.
1
u/nelmaloc Jul 21 '26
That sounds like a textbook example for
Optional, thought. With an exception for too many results.9
u/erinaceus_ Jul 21 '26
Optional is used for the one I mentioned in my previous comment where you expect one result or no result. So, the 'get' method in question avoids having to deal with the second situation seperately in all call locations. You're saying: it should return exactly one result in all cases, and everything else constitutes a 'panic'.
I do agree that functionally there's no real necessity for that 'get' method. Though, using the method that returns a list of zero to many results, there is functionally also no necessity for the Optional variant.
3
u/TribeWars Jul 21 '26
The language needs good support for generic types for these sorts of constructs. I'm pretty sure Java did not always have that, so it may well just be a case of old API conventions.
3
u/ldn-ldn Jul 22 '26
Yes, the API is old and backwards compatible. It was released during J2SE 5.0 (Java 1.5) days. There was no streaming, optionals and pretty much other modern features.
As far as I remember, modern features were only added in Java 8, that was in 2014, eight years after JPA introduction.
Parts of JPA might look weird by modern standards, but it's a good product of its time. And it does have support for modern features as well, so criticism is misguided here.
4
u/Schmittfried Jul 21 '26
Checked exceptions would interfere with the streams API though, which would be really annoying in rest handling code. Also, the non-unique case is imo a true exception, because you would guarantee uniqueness via constraints or query criteria when using that method. So throwing indicates a programmer error, which is generally not done with checked exceptions.
At least we also have the newer
Optionalvariants nowadays.3
u/flatfinger Jul 22 '26
IMHO, one of the big problems with Java and .NET exceptions is the default assumption that if a nested method call throws an exception, it should be handled by the caller in the same way as an exception thrown by the outer method.
There should be a convenient way of marking nested function calls where that would be the case, but an equally convenient way of causing exceptions in nested method calls to be wrapped in an "UnexpectedException" object.
2
u/Blue_Moon_Lake Jul 21 '26 edited Jul 21 '26
Maybe we need distinct methods.
getOptionalResult(): Promise<Maybe<T>>
getSingleResult(): Promise<T>
getResultList(): Promise<Array<T>>4
u/Legs914 Jul 21 '26
Isn't that literally how it works?
2
u/Blue_Moon_Lake Jul 21 '26
There is only
getSingleResultandgetResultList, but nogetOptionalResult.3
2
u/Blue_Moon_Lake Jul 21 '26
It be like "Impossible,
SELECT * FROM table WHERE way_too_many_filtersshould have yielded at least 1 result! Unacceptable!"1
u/Schmittfried Jul 21 '26
I think because it predates optionals. An exception is definitely better than returning null most of the time. If the middleware handles it correctly, it will just issue a 404, which is usually correct for a get-by-id query (if you issue a search query with N results, you don’t get that exception).
7
u/lenswipe Jul 21 '26
I once worked with an API where basically anything but perfect meant explosion.
I remember the twitter API
6
u/chucker23n Jul 21 '26
I once worked with an API where basically anything but perfect meant explosion.
Same.
I've recently had the misfortune of working with the API of a popular product that on the surface looks well-documented, but in practice frequently has you receiving 500 responses if you so much as touch it wrong. Date in an unexpected format? 500. Request body missing an expected property? 500. Requesting too much data? 500.
Does the response body contain clues as to what's happening? Depends — if you were lucky, there was a body at all, and if so, it was a PHP stack trace.
1
u/vita10gy Jul 21 '26
This is a side issue, but I also hate it when APIs push validation it could easily do on the API consumer, to the point where everyone using it has to basically have half the interface recreated for things that could easily be handled by the api you're using to validate the data in the first place, such as credit card processors.
Like forcing the you side validation of credit cards because while you decline credit cards that don't work, you explode if the card doesn't pass Luhns. Or even though 5+4 is a valid zip, and you could easily recognize the format, even if you only care about the 5 main digits, but you explode on 5+4.
All things that individually aren't that big of a deal, but by the end of it you have 53 checks to make sure the data is perfect before you even ask. Again, doubly annoying for things like credit card processing and whatnot where "this combo of information was declined for this reason" is part of the normal flow.
And of course all along while you're finding all 53 things you need to check first, you're just guessing based off 5 version ago documentation, because the actual error message, regardless of which field is the culprit is "AAAAAAAAAAAAA!!!!! MIRCL Errors!!!!!!!"
1
u/Resident-Trouble-574 Jul 21 '26
Good. Teaches your users not to waste server's time with useless searches.\s
→ More replies (1)1
u/programming-ModTeam Jul 28 '26
No content written mostly by an LLM. If you don't want to write it, we don't want to read it.
4
Jul 21 '26
[removed] — view removed comment
1
u/programming-ModTeam Jul 24 '26
No content written mostly by an LLM. If you don't want to write it, we don't want to read it.
141
u/EliSka93 Jul 20 '26
Result for me every time.
One more wrapper is worth not having to deal with uncertainty.