Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean error handling approach in C

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?

like image 803
Wei Shi Avatar asked Apr 07 '12 02:04

Wei Shi


1 Answers

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.

like image 164
George Skoptsov Avatar answered Nov 12 '22 17:11

George Skoptsov