检查许多函数调用时出错

use*_*545 5 c c++ error-handling recursion

有时,当我使用C++/CI进行编程时,最终多次调用相同的函数,我想知道检查所有这些调用的错误的最有效方法是什么?使用if else语句会占用大量代码并且看起来很难看.我想出了自己检查错误的方法,也许有更好的方法可以使用.

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();
}
Run Code Online (Sandbox Code Playgroud)

注:据我所知,使用trycatch可能对C更好++,因为它会通过在第一个错误抛出异常的解决了这个问题,但这个问题是,它是不是有很多的返回错误代码,如功能兼容Windows API.谢谢!

Ker*_* SB 5

你可以像这样编写一些伪C++:

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";
    }
}
Run Code Online (Sandbox Code Playgroud)


Lan*_*ens 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";
    }
    catch (...)
    {
        //Error Checking
    }
}
Run Code Online (Sandbox Code Playgroud)