Error Handling

Peter da Silva peter at ficc.ferranti.com
Mon Oct 1 07:58:25 AEST 1990


foo()
{
	stuff1
	if(!error) {
		stuff2
		if(!error) {
			stuff3
			if(!error) {
				main code
				return success;
			}
			cleanup stuff3
		}
		cleanup stuff2
	}
	cleanup stuff1
	return failure;
}

The main advantage of this form is it guarantees cleanups get performed
in the right order. It does get a bit deep, but it's just as efficient
and easier to follow than the version with gotos:

foo()
{
	stuff1
	if(error) goto exception1;
	stuff2
	if(error) goto exception2;
	stuff3
	if(error) goto exception3;
	main code
	return success;
exception3:
	cleanup stuff3
exception2:
	cleanup stuff2
exception1:
	cleanup stuff1
	return failure;
}

However, if you have a couple of dozen exceptions the latter can easily be
seen to be more readable. Just be DAMN careful that the exception recovery
ordering is maintained. Oh, you can use a case:

foo()
{
	stuff1
	state=1;
	if(error) goto exception;
	stuff2
	state=2;
	if(error) goto exception;
	stuff3
	state=3;
	if(error) goto exception;
	main code
	return success;
exception:
	switch(state) {
	case 3:
		cleanup stuff3
	case 2:
		cleanup stuff2
	case 1:
		cleanup stuff1
	}
	return failure;
}

But this comes down to the same thing, really.
-- 
Peter da Silva.   `-_-'
+1 713 274 5180.   'U`
peter at ferranti.com



More information about the Comp.lang.c mailing list