I'm using error codes for handling errors in my c++ project. The problem is how to return error codes from a function which is supposed to return some variable/object.
consider this:
long val = myobject.doSomething();
Here, myobject is an object of some class. If doSomething function encounters some error condition then how should it notify the caller (Without using exceptions).
Possible solutions:
Now how can I notify the caller about some error condition?
Most of the C or even Unix function calls return -1 or NULL in case of any error and set an error code errno. It is set as a global variable and indicates an error occurred during any function call. You can find various error codes defined in <error.
Syntax: char *strerror (int errnum) errnum: is the error number (errno).
Make a template called, say, Maybe
that it parametrized by your return value type. Whenever you return a value, wrap it in this template like this:
Maybe<long> result = object.somemethod();
The Maybe
template would have a way of being instantiated with an error code (probably a static method):
return Maybe<long>::error(code);
But ordinarily would just be returned with the value:
Maybe<long> retval; retval = 15; return retval;
(You would have to, of course, override the appropriate constructors, assignment operators, etc.)
In the client side you call a method to check for the error.
Maybe<long> result = object.somemethod(); if (result.is_error) { ... handle the error ... } else { ... use the result ... }
Again you'd need the appropriate operators defined to use Maybe<long>
wherever there's a long
required.
This sounds like a lot of work, but really the work is done once in making a good, bulletproof Maybe
template. You'll also have to do some performance tuning on it to avoid nasty overheads. If you want to make it more flexible you can parametrize it on both the return value type and the error type. (This is only a minor increase in complexity.)
You probably want something like Alexandresu's Expected<T> idiom.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With