I'm thinking of implementing exception handling in C and extractly I have written a simple one. But it's not threaded-safe. Can you have me fix it, or is there any similar implementation for exception handling?
Code:
int __cm_jmp_pos = 0;
jmp_buf __cm_jmp_buf[128];
/* exception */
/******************************************************************************/
#define cm_try_begin() \
do { \
extern jmp_buf __cm_jmp_buf[128]; \
extern int __cm_jmp_pos; \
int __jmp_ret; \
if((__jmp_ret = setjmp(__cm_jmp_buf[__cm_jmp_pos++])) == 0) \
{
#define cm_try_catch(exception) \
} \
else if(__jmp_ret == (exception)) \
{ \
extern int __cm_jmp_pos; \
__cm_jmp_pos--; \
#define cm_try_end() \
} \
else \
{ \
extern int __cm_jmp_pos; \
__cm_jmp_pos--; \
cm_try_throw(__jmp_ret); \
} \
} while(0)
#define cm_try_throw(exception) \
do { \
extern jmp_buf __cm_jmp_buf[128]; \
extern int __cm_jmp_pos; \
if(__cm_jmp_pos > 0) \
{ \
longjmp(__cm_jmp_buf[__cm_jmp_pos - 1], (exception)); \
} \
else \
{ \
fprintf(stderr, "unhandled exception %d at file %s, line %d\n", \
(exception), \
__FILE__, \
__LINE__); \
exit(EXIT_FAILURE); \
} \
} while(0)