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;
}
int function_sequence(...)
{
if (f1(...) && f2(...) && f3(...) && f4(...) && f5(...))
return SUCCESS;
else
return ERROR;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With