How to return multiple error codes from a C ++ function

What is a good way to return success or one or more error codes from a C ++ function?

I have this member function called save (), which is saved for each of the member variables. Calling the save () function requires at least ten of these member variables, I want to find out if the call failed, and if so, which member variable (some of them are hard, some are soft).

+3
source share
9 answers

You can either return an object with several error fields, or use "out'parameters".

, , . - . , "out".

"", . out , .

?

+7

, , ...

++ . , , ++ stdexcept. , , , , .

+7

boost::tuple:

typedef boost::tuple<int,int> return_value;

return_value r = my_function();

int first_value = boost::get<0>( r );
int second_valud = boost::get<1>( r );

boost::tie :

boost::tie( first_value, second_value ) = r;
+6

- std:: pair < > :

+4

:

 bool function(int& error1, int& error2, stringx& errorText, int& error3);
+2

bitset, . .

const bitset<10> a_not_set(1);
const bitset<10> b_not_set(2);
const bitset<10> c_not_set(4);

...

bitset<10> foo(T& a, T& b, T& c, ...)
{

    bitset<10> error_code = 0;

    ...


    if ( /* a can't be set */ )
    {
        error_code |= a_not_set;
    }

    ...

    if ( /* b can't be set */ )
    {
        error_code |= b_not_set;
    }

    ...

    // etc etc

    return error_code;
}

bitset<10> err = foo(a, b, c, ... );
if (err && a_not_set)
{
   // Blah.
}
+2

- (aka flags).

+2

, , . , , ++ .

, eunm .

enum error
{
   NO_ERROR = 0,

   MEMBER_0_NOT_SAVED = 1,
   MEMBER_1_NOT_SAVED = 1 << 1,
   MEMBER_2_NOT_SAVED = 1 << 2,
   // etc..

};

int save()
{
    int ret = NO_ERROR;

    // fail to save member_0
    ret  |= MEMBER_0_NOT_SAVED;

    // fail to save member_1
    ret  |= MEMBER_1_NOT_SAVED;

    // ....

    return ret; 
}

int main(void)
{
    int ret = save();
    if( ret == NO_ERROR)
    {
       // good.
    }
    else
    {
        if(ret & MEMBER_0_NOT_SAVED)
        {
              // do something
        }

        if(ret & MEMBER_1_NOT_SAVED)
        {
              // do something
        }

        // check the other errors...
    }
}

. .

+2

I am not familiar with the internal components and limitations of your project, but if possible, try using exceptions instead of error codes.

The reasons are listed here in the C ++ FAQ lite , and they end in:

Thus, compared with error messages using return codes, and if using try / catch / throw is likely to lead to code with fewer errors, less costly to develop and have faster time to market.

0
source

Source: https://habr.com/ru/post/1709559/


All Articles