C Exceptions
2005-07-18T09:55-0700
Pretty much the only thing that bugs me about C is its lack of exceptions. I can fairly easily implement most things needed for objects, however exceptions were fun. Luckily, both POSIX and C99 specify the setjmp and longjmp functions. These functions save and restore the current state of a program. Basically, I found a way to transparently use setjmp as an anchor for an exception and longjmp to raise an exception. This, of course, will NOT perform the normal C++ unrolling of the stack. In the application I'm using them in (Cpyder), this is not an issue since all memory allocation is performed in pools.
Using preprocessor macros, I've also implemented some nice
syntactic eye-candy in the form of
try { ... } catch (E) { ... } endtry;
blocks. These blocks will get translated, using the standard
c-pre-processor, into a switch. I could have elemenated the endtry
by using an if, however if's scale very poorly for these sorts of
things and switch statements offer a roughly constant execution
time.
Availability
If anyone is interested in these, just let me know.