So I ran across this (IMHO) very nice idea of using a composite structure of a return value and an exception - Expected<T>
. It overcomes many shortcomings of the traditional methods of error handling (exceptions, error codes).
See the Andrei Alexandrescu's talk (Systematic Error Handling in C++) and its slides.
The exceptions and error codes have basically the same usage scenarios with functions that return something and the ones that don't. Expected<T>
, on the other hand, seems to be targeted only at functions that return values.
So, my questions are:
- Have any of you tried
Expected<T>
in practice? - How would you apply this idiom to functions returning nothing (that is, void functions)?
Update:
I guess I should clarify my question. The Expected<void>
specialization makes sense, but I'm more interested in how it would be used - the consistent usage idiom. The implementation itself is secondary (and easy).
For example, Alexandrescu gives this example (a bit edited):
string s = readline();
auto x = parseInt(s).get(); // throw on error
auto y = parseInt(s); // won’t throw
if (!y.valid()) {
// ...
}
This code is "clean" in a way that it just flows naturally. We need the value - we get it. However, with expected<void>
one would have to capture the returned variable and perform some operation on it (like .throwIfError()
or something), which is not as elegant. And obviously, .get()
doesn't make sense with void.
So, what would your code look like if you had another function, say toUpper(s)
, which modifies the string in-place and has no return value?