Clean error handling approach in C
c, error-handling
Solution
Some people, especially beginner-to-intermediate programmers, have a very idiosyncratic reaction to seeing `goto` in production code, but the usual idiom for sequential acquiring of resources and their intelligent release upon error is the following:
if(doWork("A") < 0)
goto errA;
if(doWork("B") < 0)
goto errB;
if(doWork("C") < 0)
goto errC;
/* success! */
return 0;
/* Error handling / releasing resources section */
errC:
undoWork("B");
errB:
undoWork("A");
errA:
return -1;
You will see plenty of examples in system code, e.g. in the linux kernel.
Problem
I'm writing a C program that needs good error handling. The code likes like this: ``` If(doWork("A")<0){ return -1; } If(doWork("B")<0){ undoWork("A"); return -1; } If(doWork("C")<0){ undoWork("A"); undoWork("B"); return -1; } return 0; ``` This code works but looks very messy, especially I have a long list of `doWork(X)` to call. Is there a better and cleaner approach to handle error in this case?