by mikevm · 13y ago · 0 comments
I remember writing some code in C a few years ago and I needed a place in a function where cleanup is performed, and in case there were errors caught in multiple places before you get to the cleanup area, I used a goto statement to jump there after printing the error message and turning on a special error flag.
How would you solve that problem without goto?
init;
do {
stuff;
if (fail) continue;
morestuff;
} while (0);
cleanup;
Which I've seen in real code released to the public. Whoever does either of those things instead of just using a goto should be flogged in the town square.edit: Other usually-bad alternatives to goto are the pyramid-of-nested-ifs or a set of running "bad" flags/enum that disables each operation downstream of the error until the cleanup is reached.
In the example you gave, the problem is that C lacks something like exceptions and that there is no automatic way for cleanup code to be called. In Java, you can use try...finally, and so you can put your cleanup code in the finally block, and other languages have similar constructs. Unfortunately, in many languages, throwing an exception from a finally block will cause one of the exceptions (often the first) to be "forgotten," which is probably a bad thing; this is also hard to deal with in C, however, since an error that occurs in your cleanup code would need to be signaled somehow, but you can only return one value from the function -- so would you return the error that triggered the cleanup, or the error that resulted from the cleanup?
That's a good question. Fortunately, I don't do anything complicated in the cleanup zone - mostly closing handles and freeing memory.
Closing handles could cause an error! Take a look at the close manpage; there are three error conditions:
* The argument is a bad file descriptor
* The call was interrupted by a signal
* An I/O error occurred while reading or writing
Reading or writing? Yes, as it turns out, closing a handle may involve I/O to perform the last synchronization of the file.
It sounds like you would ignore errors caused by closing the handle, and you would signal whatever error caused the cleanup to be entered.
At the same time, if your methods are complicated enough to possibly require multiple exit points, I'd argue that they should be refactored and broken apart a bit more.
I don't think there's anything wrong with using goto in such a case, though, if it makes the code more understandable.
[1] http://eli.thegreenplace.net/2009/04/27/using-goto-for-error...
I wouldn't bother trying, at least in C.