Error Handling
Vasile R. Montan
vrm at cathedral.cerc.wvu.wvnet.edu
Fri Sep 28 01:15:21 AEST 1990
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
More information about the Comp.lang.c
mailing list