对于以下代码结构:
int function_sequence(...)
{
f1(...);
f2(...);
f3(...);
f4(...);
f5(...);
return SUCCESS;
}
哪种错误处理方式更容易接受?
此:
int function_sequence(...)
{
if(f1(...)){
// Error handling
return ERROR;
}
if(f2(...)){
// Error handling
return ERROR;
}
...
return SUCCESS;
}
或者这个:
int function_sequence(...)
{
if(f1(...)){
goto error;
}
if(f2(...)){
goto error;
}
...
return SUCCESS;
error:
// Error handling
return ERROR;
}
答案 0 :(得分:3)
对于C,我更喜欢你的第二个选择。
此外,逐步清理(免费分配内存等)非常有用,就像Linux内核一样:
int function_sequence(...)
{
if(f1(...)){
goto error1;
}
if(f2(...)){
goto error2;
}
...
return SUCCESS;
error2:
cleanup2();
error1:
cleanup1();
// Error handling
return ERROR;
}
答案 1 :(得分:3)
int function_sequence(...)
{
if (f1(...) && f2(...) && f3(...) && f4(...) && f5(...))
return SUCCESS;
else
return ERROR;
}
答案 2 :(得分:1)
我喜欢的方式是以下内容:
int function_sequence(...)
{
int res=0;
if(f1(...)){
goto ENDF;
}
if(f2(...)){
goto ENDF;
}
...
res = 1;
ENDF:
if(res ==0)
{
//Error handling
}
//Success and Error stuff to do (like free...).
return res;
}
所以只有一次回归,有时候两种行为都要做:错误和成功(例如免费......)。
我想我的观点可以讨论。
答案 3 :(得分:1)
如果这是一个特殊的事情,使该功能不起作用,抛出异常。
如果您有理由坚持返回代码,可以使用
if ( f1() && f2() && .... )
return SUCCESS;
else
return ERROR;
执行将在遇到第一个false
或0
后停止,因此效果与您的版本几乎相同。
有些库会在成功时返回0
(呵呵,即使是C ++的main
也是如此)。所以你可能想要
if ( !f1() &&.... )
或简单的
return f1() && f2() &&.... ;
答案 4 :(得分:1)
这是我通常使用的
int function_sequence(...)
{
if(f1(...)){
goto error1;
}
if(f2(...)){
goto error2;
}
return SUCCESS;
}
error1:
// Error 1 handling
return -eerno1;
error2:
// Error 2 handling
return -eerno2;
//end of main
答案 5 :(得分:0)
在C中,我使用第三个选项:
int function_sequence(...)
{
bool ok = true;
if (ok) ok = f1(...);
if (ok) ok = f2(...);
if (ok) ok = f3(...);
if (ok) ok = f4(...);
if (ok) ok = f5(...);
if (!ok) error_handling();
cleanup(); // Your example didn't have this, but it's often here.
return ok ? SUCCESS : ERROR;
}