在直接 C 程序中处理错误的任何好的习惯用法? [英] Any good idioms for error handling in straight C programs?
本文介绍了在直接 C 程序中处理错误的任何好的习惯用法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
重新开始一些 C 工作.
Getting back in to some C work.
我的许多函数看起来像这样:
Many of my functions look like this:
int err = do_something(arg1, arg2, arg3, &result);
意图结果由函数填充,返回值是调用的状态.
With the intent the result gets populated by the function, and the return value is the status of the call.
阴暗面是你会得到这样的天真:
The darkside is you get something naive like this:
int err = func1(...);
if (!err) {
err = func2(...);
if (!err) {
err = func3(...);
}
}
return err;
我想我可以对其进行宏处理:
I could macro it I suppose:
#define ERR(x) if (!err) { err = (x) }
int err = 0;
ERR(func1(...));
ERR(func2(...));
ERR(func3(...));
return err;
但这仅在我链接函数调用而不是做其他工作时才有效.
But that only works if I'm chaining function calls, vs doing other work.
显然,Java、C#、C++ 有异常适用于这些类型的事情.
Obviously Java, C#, C++ have exceptions that work very well for these kinds of things.
我只是好奇其他人在做什么以及其他人现在如何在他们的 C 程序中进行错误处理.
I'm just curious what other folks do and how other folks do error handling in their C programs nowadays.
推荐答案
两种典型模式:
int major_func()
{
int err = 0;
if (err = minor_func1()) return err;
if (err = minor_func2()) return err;
if (err = minor_func3()) return err;
return 0;
}
int other_idea()
{
int err = minor_func1();
if (!err)
err = minor_func2();
if (!err)
err = minor_func3();
return err;
}
void main_func()
{
int err = major_func();
if (err)
{
show_err();
return;
}
happy_happy_joy_joy();
err = other_idea();
if (err)
{
show_err();
return;
}
happy_happy_joy_joy();
}
这篇关于在直接 C 程序中处理错误的任何好的习惯用法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文