应用程序内的 C 错误处理

标签 c error-handling

帖子Error handling in C code描述了 C 库中的错误处理,但我想知道如何处理您自己的应用程序中的错误。

我即将编写我的第一个 C 应用程序,并且正在考虑两种错误处理样式:返回错误代码和返回错误消息。

// 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;
}

你的意见是什么?我想知道现实世界应用程序中最常用的方式是什么?谢谢。

最佳答案

我通常更喜欢错误代码。如果您对 C 中的正确错误处理感兴趣,我建议您阅读 CERT secure coding recommendations and rules

此外,为了返回错误代码,我倾向于使用日志记录。例如以下宏。

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

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

返回案例可能如下所示

if (!something) {
   LOG_WARNING("Something bad happend");
   return (-1);
}

关于应用程序内的 C 错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36166512/

相关文章:

android - 使用api的Android和jsonParsing不起作用

c/windows : opening all . 目录中的 txt 文件

c - 编写函数原型(prototype)的明智方法

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

exception - 除以零是错误还是异常?

c# - 类x.Savechanges(): No suitable method found to override

swift - 抛出函数不会退出执行函数

c - 返回语句中的奇怪表达式

c - 使用 pthreads 来加速从 0 到 N 计算质数的处理。我使用它们是否正确?

c - 表达式中移位和按位补码的反转优先级