Error checking in many function calls

Sometimes, when I program in C ++ / C, I end up calling the same function several times, and I was wondering what is the most efficient way to check for errors for all these calls? Using statements if elsetakes a lot of code and looks ugly. I came up with my own way to check for errors, maybe there is a better way that I should use.

int errs[5] = {0};
errs[0] = functiona(...);
errs[1] = functiona(...);
...
errs[5] = functiona(...);
for (int i = 0; i < 5; i++)
{
  if (err[i] == 0)
     MAYDAY!_wehaveanerror();
}

Note. I understand that using tryand catchmay be better for C ++, since it will solve this problem by throwing an exception on the first error, but the problem is that it is incompatible with a large number of functions that return error codes, such as the Windows API. Thank!

+5
5

... , catch.

struct my_exception : public std::exception {
    my_exception(int); /* ... */ };

int main()
{
    try
    {
        int e;
        if ((e = function()) != SUCCESS) { throw my_exception(e); }
        if ((e = function()) != SUCCESS) { throw my_exception(e); }
        if ((e = function()) != SUCCESS) { throw my_exception(e); }
    }
    catch (my_exception & e)
    {
        std::cerr << "Something went wrong: " << e.what() << "\n";
    }
    catch (...)
    {
        //Error Checking
    }
}
+2

-++, :

struct my_exception : public std::exception {
    my_exception(int); /* ... */ };

int main()
{
    try
    {
        int e;
        if ((e = function()) != SUCCESS) { throw my_exception(e); }
        if ((e = function()) != SUCCESS) { throw my_exception(e); }
        if ((e = function()) != SUCCESS) { throw my_exception(e); }
    }
    catch (my_exception & e)
    {
        std::cerr << "Something went wrong: " << e.what() << "\n";
    }
}
+5

?

void my_function() {
  if (!create_window())
    throw Error("Failed to create window");
}

int main() {
  try {
    my_function();
  } catch (const Error& e) {
    cout << e.msg << endl;
  } catch (...) {
    cout << "Unknown exception caught\n"
  }

  return 0;
}
+1

If you call the same function over and over, the shortest way might be to use a macro. I would suggest something like:

#define CHECKERROR(x) if(x == 0) wehaveanerror()

CHECKERROR(function(...));
CHECKERROR(function(...));

Obviously, this macro will be very specific to a particular function and error handler, so it may be reasonable for undefafter these calls.

0
source

Doing this an older school, but keeping the original error response, but responding as soon as the error occurs, not looking ugly:

#define callcheck(r) if ((r)==0) MAYDAY!_wehaveanerror()

callcheck(functiona(...));
callcheck(functiona(...));
...
0
source

All Articles