C错误处理编码风格 [英] C error handling coding-style
本文介绍了C错误处理编码风格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在以下代码结构的情况下:
int function_sequence(...)
{
f1(...);
f2(...);
f3(...);
f4(...);
f5(...);
return SUCCESS;哪一种错误处理方式更容易接受?
$ b}
<
$ b
This:
int function_sequence(...)
{
if(f1(...)){
//错误处理
return ERROR;
}
if(f2(...)){
//错误处理
return ERROR;
}
...
返回SUCCESS;
}
或者:
int function_sequence(...)
{
if(f1(...)){
goto error;
}
if(f2(...)){
goto错误;
}
...
return SUCCESS;
错误:
//错误处理
return ERROR;
}
解决方案
第二个选项。
此外,有用的是逐步清理(释放分配的内存等),如Linux内核:
int function_sequence(...)
{
if(f1(...)){
goto error1;
}
if(f2(...)){
goto error2;
}
...
return SUCCESS;
error2:
cleanup2();
error1:
cleanup1();
//错误处理
return ERROR;
}
In the case of the following code structure:
int function_sequence(...)
{
f1(...);
f2(...);
f3(...);
f4(...);
f5(...);
return SUCCESS;
}
Which way of the error handling is more acceptable?
This:
int function_sequence(...)
{
if(f1(...)){
// Error handling
return ERROR;
}
if(f2(...)){
// Error handling
return ERROR;
}
...
return SUCCESS;
}
Or this:
int function_sequence(...)
{
if(f1(...)){
goto error;
}
if(f2(...)){
goto error;
}
...
return SUCCESS;
error:
// Error handling
return ERROR;
}
解决方案
For C, I prefer your second option.
Further, it's useful to do gradual cleanup (free allocated memory and so on), like in Linux kernel:
int function_sequence(...)
{
if(f1(...)){
goto error1;
}
if(f2(...)){
goto error2;
}
...
return SUCCESS;
error2:
cleanup2();
error1:
cleanup1();
// Error handling
return ERROR;
}
这篇关于C错误处理编码风格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文