Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the right approach to return error codes in C++

Tags:

c++

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:

  1. Have a data member (say err_) in the class which can be checked by the caller. But it would be unsafe in a multi-threaded application sharing the same object and calling the same function.
  2. Use some global error variable, again same issue in a multi-threaded environment.

Now how can I notify the caller about some error condition?

like image 812
Jeet Avatar asked Jul 01 '10 10:07

Jeet


People also ask

What is error return C?

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.

Which function is used to capture the error code?

Syntax: char *strerror (int errnum) errnum: is the error number (errno).


2 Answers

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.)

like image 83
JUST MY correct OPINION Avatar answered Sep 25 '22 04:09

JUST MY correct OPINION


You probably want something like Alexandresu's Expected<T> idiom.

like image 37
Christopher Smith Avatar answered Sep 25 '22 04:09

Christopher Smith