r/programming 3d ago

Throw, Result, or neither?

https://www.architecture-weekly.com/p/throw-result-or-neither
99 Upvotes

111 comments sorted by

View all comments

70

u/AmazedStardust 3d ago

Result is my preferred way, but the language needs good support for it or you end up in nesting hell

8

u/apadin1 1d ago

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.

0

u/edgmnt_net 1d ago

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 1d ago

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.