mardi 22 mars 2016

C error handling withing an application

The post Error handling in C code describes the error handling in C library, however I'm wondering how to handle errors within your own application.

I'm about to write my first C application, and I'm considering of two error handling styles: returning error code and returning error messages.

// error code style
#define INTERNAL_ERROR 3
int foo(void)
{
   int rc = third_party_lib_func();
   if (rc) {
       return INTERNAL_ERROR;
       // pro: looks nice and clean, everyone talks about error code
       // con: it is hard to debug, what error comes from the third 
       // party function?
   }
   return 0;
}

// error message style
char *foo(void)
{
    int rc = third_party_lib_func();
    if (rc) {
        char *errstr = third_party_lib_strerror(rc);
        return errstr;
        // pro: golang style, easy to check by foo() == NULL,
        //      easy to debug
        // con: maybe it is an rare error handling approach?
    }
    return NULL;
}

What is your opinion? And I'm wondering what is the most common way used in the real world application? Thanks.



C error handling withing an application

Aucun commentaire:

Enregistrer un commentaire