Saturday, September 21, 2019

Simplest Exceptions Handler Macros for C

More adventures in C, I revisited my exception handler implementation libex. I realized there's an even simpler version that's more efficient if we give up the requirement that exceptions can be propagated to callers:

#define TRY
#define THROW(E) goto E
#define CATCH(E) goto FINALLY_H; E:
#define FINALLY FINALLY_H:

This implementation requires only a single exception handling block per function, which is probably good idea as a general rule. Usage looks like:

static void foo(size_t sz) {
  char* x;
  TRY {
    x = (char*)malloc(sz);
    if (x == NULL) THROW(ENoMem);
    // do something with x
  } CATCH(ENoMem) {
    // handle out of memory
  } FINALLY {
    if (x != NULL) free(x);
  }
}

Unlike libex, this version is actually compatible with break and continue, although using them runs the risk of skipping the FINALLY handler. An almost equally simple version of exception handlers which ensures that break/continue cannot skip the FINALLY block wraps everything in a loop:

#define TRY do {
#define THROW(E) goto E
#define CATCH(E) goto FINALLY_H; E:
#define FINALLY } while(0); FINALLY_H:

This ensures that any break or continue statements executed within the TRY or CATCH blocks immediately exit to the FINALLY handler.

Of course, abort() and exit() invocations will also bypass FINALLY, so if you intend to use these macros, I suggest using them only as a way to organize your code in a more structured fashion.

No comments: