Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!wuarchive!udel!haven!cs.wvu.wvnet.edu!cerc.wvu.wvnet.edu!cathedral!vrm From: vrm@cathedral.cerc.wvu.wvnet.edu (Vasile R. Montan) Newsgroups: comp.lang.c Subject: Error Handling Keywords: Errors Message-ID: <837@babcock.cerc.wvu.wvnet.edu> Date: 27 Sep 90 15:15:21 GMT Sender: news@cerc.wvu.wvnet.edu Lines: 65 Here is a general question to all of the expert C programmers, or even novice C programmers, who have a strong opinion on C style. What is the best way for a function to check for errors and return an error code? This sounds like a simple problem, but I don't know which way to go. I would just like to follow a style which is easy to maintain. Below are the methods which I have considered so far. You may add new ones if you like. I apologize for any other style problems in my example code. I was trying to make the examples small. I will post a summary of all replies that I get through email. Method 1: Return Error Code When Error Is Encountered The problems I have with this are first it goes against software engineering principles which say that all functions should have one entry point and one exit point. Secondly some functions do have some standard clean up to do. int function() { int error; if (error = check1()) {cleanup(); return error;} if (error = check2()) {cleanup(); return error;} if (error = check3()) {cleanup(); return error;} cleanup(); return NOERROR; } Method 2: Set Error Code and Return Only at End The problem I have with this is that I don't want to do later work if a previous error occured. I just want to clean up and return. This forces me to continuously check if a previous error occured. int function() { int error; error = check1(); if (!error) error = check2(); if (!error) error = check3(); cleanup(); return error; } Method 3: Use GOTO to Create Exception Handler Of course this breaks the golden rule of software engineering of "absolutely positively no GOTO's in your program." int function() { int error; if (error = check1()) goto exception; if (error = check2()) goto exception; if (error = check3()) goto exception; cleanup(); return NOERROR; exception: cleanup(); return error; } Thanks for your time, -- Vasile