简体   繁体   中英

Handle errors C++

So, I have a simple library-class and this class has some methods that return some values like code errors.

User_program

MyClass go(arg1, arg2)
if(go.execute() == 0)
  std::cout << go.result();

And my class has something like this

My class

int execute()
{

    if((temp = doBar()) != 0)
    {
         return temp;
    }
    return SUCCESS;
}

int doBar()
{
   if(foo == 1)
      return DIVIDION_BY_ZERO;
   if(fzz == 0)
      return OPERATION_ERROR;
}

And so on. So, is there any method to make errors more helpful, I've heard about enum with const for errors, but I don't understand how to implement it.

Thanks.

Not sure that I understood the question right, but here is few moments.

  1. In your case enum`s is way to store all definitions of const values like (SUCCESS, DIVIDION_BY_ZERO, etc) in one place (even in one translation unit). And also compiletime validation of types. read more here: [1]
  2. 2) If intresting how implemented some error check there is no need to go far.

    • First of all look at C handling errors in libc [2]
    • In ISO C++11 presented [system_error]
    • And typical error handling in libs released special for (almost) each type like in Qt [QNetworkReply]
  3. And also using exceptions(and dark side of C++ like RTTI) in libs is bad idea. But take this link too [3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM