Any good idioms for error handling in straight C programs? Any good idioms for error handling in straight C programs? c c

Any good idioms for error handling in straight C programs?


If you have resources that need to be released at the end, then sometimes the old trusty goto can be handy!

intmajor_func(size_t len){    int err;    char *buf;    buf = malloc(len);    if (err = minor_func1(buf))        goto major_func_end;    if (err = minor_func2(buf))        goto major_func_end;    if (err = minor_func3(buf))        goto major_func_end;major_func_end:    free(buf);    return err;}


Two typical patterns:

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();}


What are you doing in the else statements? If nothing, try this:

int err = func1(...);if (err) {    return err;}err = func2(...);if (err) {    return err;}err = func3(...);return err;

This way you're short-circuiting the entire function, not even bothering with the following function calls.

EDIT

Going back and reading again, I realize that it doesn't matter what you do in your else statements. That sort of code can easily go immediately after the if blocks.