-3

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.

Community
  • 1
  • 1
Eathen Nutt
  • 1,433
  • 5
  • 19
  • 27

1 Answers1

1

I usually prefer error codes. If you're interested in proper error handling in C, I recommend reading the CERT secure coding recommendations and rules .

Additionally to return error codes I tend to use logging. For example the following macros.

/* defining some error logging macros */
#define LOG_ERROR(...)            \
  do {                            \
    errx(1, __VA_ARGS__);         \
  } while(0)

#define LOG_WARNING(...)          \
  do {                            \
    warnx(__VA_ARGS__);           \
  } while(0)

A return case could look like

if (!something) {
   LOG_WARNING("Something bad happend");
   return (-1);
}
mkind
  • 2,015
  • 2
  • 20
  • 25