[net.unix-wizards] Error Handling in C

donn (10/27/82)

Reference: rocheste.135 "Error checking in C"

I personally think that "exception" statements in C would be grossly
machine and library dependent and I don't think they should be
implemented so as to change the syntax of the language.  On the other
hand they are one way of providing a heavily needed feature to the
typical C programming environment.  I myself attempt to test every I/O
operation individually in my significant programs and return a useful
error status, but many people don't do this and this frequently leads
to problems with distributed programs.  The effort of writing these
tests is such that I don't bother with them in trivial programs, but
even there it would be a useful debugging aid if such things were
caught automatically.  Some people advocate that the default behavior
for errors detected in library routines should be an abort with core
dump, and I can appreciate the usefulness of this (although I wouldn't
like it to be the standard).

There is evidence that someone once thought of a nice alternative to
exception statements, at least for standard library errors.  There is a
file called 'macros.h' in the 2.8 distribution which contains a macro
ERRABORT() which purports to cause library functions to abort on error
rather than return NULL or something like that.  It works by defining a
function '_error' which simply calls 'abort'.  Presumably a version of
the library existed in which '_error' was called before returning from
any error, in which case you got a core dump telling you what was going
on when you bombed.  (The 2.8 library shows no evidence of such a
system, incidentally.  I have no idea whose 'macros.h' file this
is...)  I can think of an even nicer way to implement this, namely to
define a global function pointer '(*fexit)()' which is called with
useful information like the severity of the error or the name of the
main library routine it bombed from and by default points to the null
function.  You could then arrange to abort on every error by saying
'fexit = abort;' in your 'main' routine.  If you wanted your own error
handling you could put it together any way you wanted, and then set
'fexit' to its entry point.  If you wanted to locally change the error
procedure for any reason, you could just change 'fexit' before entering
the sensitive code.

I think this would handle most of the problems.  I know it would help
prevent one major complaint from C neophytes ("why doesn't it just stop
when something goes wrong?").  Comments?

Donn Seeley  UCSD Chemistry Dept. RRCF  ucbvax!sdcsvax!sdchema!donn