gpt4 book ai didi

应用程序内的 C 错误处理

转载 作者:行者123 更新时间:2023-11-30 21:01:15 25 4
gpt4 key购买 nike

帖子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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com