Error handling using goto
developmentThe project uses the goto pattern for error handling, similar to the Linux kernel. This pattern reduces code duplication and keeps the primary function logic clear.
Pattern:
- Use
gototo jump to error-handling labels. - Name labels after the most recent resource acquired that needs to be freed.
- This is particularly effective when functions return a
result_ttype.
void func() {
result_t r = RESULT_OK;
if((r = sm_init()) != RESULT_OK) { goto fail; }
if((r = bsd_init()) != RESULT_OK) { goto fail_sm; }
// code goes here
bsd_finalize();
fail_sm:
sm_finalize();
fail:
return r;
}