Let me share one of my favorite little programming idioms … do { … } while (false);

I picked it up from a friend who learned it from a friend, who probably saw it in a book. It may seem like a do-nothing, but it is a very nice low-budget and high performance exception handling mechanism. The typically application is something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// setup
int status = 0;

do {
   // preconditions
   status = doSomething();
   if (status) break;
   status = doSomethingElse();
   if (status) break;

   // computation
   status = doWhatYouWantedToInTheFirstPlace();
} while (false);

// cleanup
return status;

Without the DWF mechanism, the same code either requires either exceptions, duplicating cleanup code, or writing deeply nested if statements until all your preconditions are satisfied. Even though DWF initially may seem a little unorthodox, the code is actually very clear, readable, and maintainable.