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?
Some people, especially beginner-to-intermediate programmers, have a very idiosyncratic reaction to seeing
gotoin production code, but the usual idiom for sequential acquiring of resources and their intelligent release upon error is the following:You will see plenty of examples in system code, e.g. in the linux kernel.