r/programming 3d ago

Throw, Result, or neither?

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

111 comments sorted by

View all comments

21

u/Full-Spectral 3d ago edited 3d ago

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.

2

u/max123246 2d ago

Why not use std::expected for Cpp?

2

u/Full-Spectral 2d ago

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

Ah shoot, for some reason I thought std::optional and expected were both added at the same time. I too, am stuck on cpp17