Monday May 12, 2008 Found myself having to act on a set of things, in some specific order. Certain items are exceptional and if present then processing stops there. The common idioms for this, that I've seen in C, are:
The former is common enough (though, not in your code nor mine, of course
) to make this blog posting worthwhile.
The latter is the neater approach, and possibly the only remaining legitimate use of goto today. However, it requires placing labels - which isn't error-proof - and maintaining discipline to not abuse (those labels are so tempting!). Some languages have dedicated syntax exception handling (try/throw/catch/finally), but these can feel a tad over-wrought for simple, localised exception handling.
There's another possibility though, generic to all C-like-syntax languages even, using a single-loop:
do {
if (foo)
do_stuff (foo);
if (bar)
break;
if (acme)
do_stuff (acme);
} while (0);
do_final_stuff();
The do {} while (0); pattern is of course already widely used in C, to encapsulate function-like macros. However, I've not personally seen it used in code bodies for such light-weight exception handling.
Another variant, that allows for some basic exception processing:
do {
if (foo)
do_stuff (foo);
if (bar)
break;
if (acme)
do_stuff (acme);
return;
} while (0);
do_exceptional_stuff();
( May 12 2008, 01:22:44 AM IST )
Permalink
Comments [0]