Newsgroups: comp.lang.c Path: utzoo!henry From: henry@zoo.toronto.edu (Henry Spencer) Subject: Re: Error Handling Message-ID: <1990Sep28.155949.24973@zoo.toronto.edu> Organization: U of Toronto Zoology References: <837@babcock.cerc.wvu.wvnet.edu> Date: Fri, 28 Sep 90 15:59:49 GMT In article <837@babcock.cerc.wvu.wvnet.edu> vrm@cathedral.cerc.wvu.wvnet.edu (Vasile R. Montan) writes: >What is the best way for a function to check for errors and return an error >code? ... >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. What you have encountered is one of the numerous situations where an arbitrary one-entry-one-exit rule just creates too much grief. Such principles should be taken as guidelines, not as Holy Law. Multiple exit points do make it harder to trace precisely where the function exited during a particular run. On the other hand, they can make the function's logic simpler by clearing away exceptional conditions and letting the code focus on the main-line case. My experience is that the latter consideration is usually more important than the former. As for standard cleanup, this *is* a pain of using multiple returns. Sometimes you can solve this by breaking the function up, putting the cleanup in an outer function where it always gets done after return from the inner one. >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. I don't recommend this. It's taking the Holy Law to ridiculous extremes. >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." See above comments on Holy Law. :-) That having been said, my own feeling is that such situations do generally represent a failure of structuring. However, I don't mean "there ought to be a way to write this function without a goto" -- that leads to the flag-variable syndrome you allude to in Method 2. What I mean is "there ought to be a way to *design* this function's *interface* that would yield a clean internal implementation". -- Imagine life with OS/360 the standard | Henry Spencer at U of Toronto Zoology operating system. Now think about X. | henry@zoo.toronto.edu utzoo!henry