Overall, I agree. Exceptions are messy and make it difficult to reason about code. That said, I think the macro at the bottom is even worse. I think a better solution to the one posted in the article is to use std::expected
instead. This gives you a typed union that allows you to return either a successful result or an error type.
What's nice about it is that you don't need to add endless amounts of if success {...} else {...}
blocks. You can use the monadic operations (and_then
, transform
, etc.) to add your logic as normal while letting the compiler smoothly take care of doing the error checks. (In fact, I really wish golang has something similar to this, it would get rid of the endless error checking you have to write manually.)
I wasn't able to find an example using std::expected
, and I tried writing one myself, but my version of g++ doesn't seem to support it yet. But here is a nice std::optional
example that should be pretty close to what you would do with std::expected
.