To answer your question, this is not a ridiculous idea, and you can use std::exception to regularly handle errors; with some reservations.
Using std::exception as a result of a function
Let's say that a function can exit several error states:
std::exception f( int i ) { if (i > 10) return std::out_of_range( "Index is out of range" ); if ( can_do_f() ) return unexpected_operation( "Can't do f in the current state" ); return do_the_job(); }
How can you handle this with std::exception or optional? When the function returns, a copy of the exception will be created, containing only the std::exception and rejecting the specification of the actual error; leaving you the only information that "yes, something went wrong ...". The behavior will be the same as returning a logical or optional expected result type, if any.
Using std::exception_ptr to save specifications
Another solution would be to apply the same approach as in std :: prom , i.e. return std::exception_ptr . There you can return either nothing or an exception, while maintaining the actual error data. Recovering the actual type of error can be difficult.
Return an error or result in the same object
Finally, another option would be to use the Expected<T> clause and its implementation . There you can return a value or error in one object and process this error if you want (by checking for errors or with regular exception handling), with some features for a function that does not return a value (more on Stack Overflow or this blog ).
How to choose
My personal opinion on this is that if you intend to use exceptions, use them the way they were designed, eventually using some additional tools, such as Expected<T> , to simplify it. Otherwise, if you cannot use standard exception handling, then move on to a solution that has established itself as a classic system of error codes.
Julien
source share