A minimal try/catch/finally pattern for vanilla C, built on setjmp/longjmp
and a per-thread stack of contexts. Two files: mintry.h and mintry.c.
#include "mintry.h"
/* volatile: assigned in MINTRY_TRY, read after MINTRY_THROW */
char* volatile p = NULL;
MINTRY_TRY (ctx) {
if (!(p = malloc (n))) MINTRY_THROW (MinTry_ExceptionType_Allocation);
...
} MINTRY_CATCH (ctx, MinTry_ExceptionType_Allocation) {
...
} MINTRY_CATCHALL (ctx) {
...
/* anything no MINTRY_CATCH above took */
} MINTRY_FINALLY (ctx) {
/* always runs; required */
free (p);
}Locals that are modified inside the MINTRY_TRY body and read in a
MINTRY_CATCH, MINTRY_CATCHALL, MINTRY_FINALLY, or after the block must be
declared volatile. This is the standard setjmp/longjmp rule
(C11 7.13.2.1p3): without volatile the compiler may keep such a variable in a
register that longjmp does not restore, and its value after a MINTRY_THROW
is indeterminate. The symptom is code that works at -O0 and silently
misbehaves at -O2.
- Exception codes are non-zero
ints.MinTry_ExceptionType_None(0) means "nothing thrown" and may not be thrown. - The first matching
MINTRY_CATCHwins.MINTRY_CATCHALLtakes whatever no earlierMINTRY_CATCHtook. MINTRY_FINALLYis mandatory, even with an empty body. It pops the context on the normal path and rethrows an exception that no handler took to the enclosingMINTRY_TRY. An exception with no enclosingMINTRY_TRYprints a message and aborts.- The context is popped as soon as an exception is delivered, so a
MINTRY_THROWinside aMINTRY_CATCHorMINTRY_FINALLYbody goes to the enclosingMINTRY_TRY. Rethrow withMINTRY_THROW (ctx.code). Returning from aMINTRY_CATCHis safe. - Exceptions cross function boundaries. The context stack is thread-local.
- Don't
return,break, orgotoout of theMINTRY_TRYbody itself: the context stays on the stack. Jumping out of aMINTRY_CATCHorMINTRY_FINALLYbody is safe but skips the rest of that block (including a pending rethrow). - A
MINTRY_THROWfrom inside aMINTRY_CATCHskips the current block'sMINTRY_FINALLY. MINTRY_TRY (ctx)declares a variable namedctx, so each block in a scope needs its own name andMINTRY_TRYcan't directly follow a label.- Requires C11 or later, or C++11 or later; the header rejects anything older
with
#error. In C++ it is usable from C-style code, butMINTRY_THROWis alongjmpand skips destructors between theMINTRY_THROWand theMINTRY_TRY, which is undefined behaviour if any of them is non-trivial.
make test # strict warnings
make test-san # same, under AddressSanitizer + UBSan
make test-cxx # test suite compiled as C++11