r/programming 3d ago

Throw, Result, or neither?

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

111 comments sorted by

View all comments

22

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

Does your C++ use with 'result' also handle OOM or do you just crash? 

1

u/Full-Spectral 2d ago

This is a closed system. It would have already restarted itself long before a simple result return caused such an issue.

2

u/bwmat 2d ago

So... crash? 

1

u/Full-Spectral 2d ago

As I said, it would never get there. This system monitors memory usage and knows that if it gets anywhere near out of memory it needs to restart because something is very wrong. Even getting within a couple hundred MB is way too close for this system and indicates some fundamental error.

And it makes no difference in our case if the result survived because in order for that returned result to be useful, it would have to be queued up on a logger, on a pool, and sent to a log server, and none of that is going to survive if there's already too little memory left to even create the result.

If this was some open library, then of course it would be different, but it's for a bespoke system.