Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error checking on many function calls

Sometimes when I am programming in C++/C I end up calling the same function multiple times and I was wondering what is the most efficient way to check for errors for all of those calls? Using if else statements take up a lot of code and look ugly. I have come up with my own way of checking for errors, perhaps 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 try and catch might be better for C++ as it would solve this problem by throwing an exception on the first error, but the problem with that is that it is not compatible with a lot of functions that return error codes such as the Windows API. Thanks!

like image 742
user99545 Avatar asked Apr 14 '12 23:04

user99545


3 Answers

You could write some pseudo-C++ like this:

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";
    }
}
like image 178
Kerrek SB Avatar answered Oct 07 '22 12:10

Kerrek SB


If...IF the function has a chance to throw a different error you should also add a catch all.

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
    }
}
like image 31
Landin Martens Avatar answered Oct 07 '22 10:10

Landin Martens


What about handling the checking in a function?

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;
}
like image 23
keelerjr12 Avatar answered Oct 07 '22 11:10

keelerjr12