Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C error handling coding-style [closed]

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;
}
like image 285
Alex Avatar asked Dec 27 '22 08:12

Alex


2 Answers

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;
}
like image 65
hate-engine Avatar answered Dec 28 '22 21:12

hate-engine


int function_sequence(...)
{
    if (f1(...) && f2(...) && f3(...)  && f4(...) && f5(...)) 
        return SUCCESS;
    else
        return ERROR;
}
like image 21
David Ranieri Avatar answered Dec 28 '22 21:12

David Ranieri