Skip to content

Instantly share code, notes, and snippets.

@cleure
Created April 26, 2012 17:09
Show Gist options
  • Save cleure/2501036 to your computer and use it in GitHub Desktop.
Save cleure/2501036 to your computer and use it in GitHub Desktop.
Primitive try/catch Exception Handling in C
#include <stdio.h>
#include <setjmp.h>
struct Exception {
jmp_buf jb;
int code;
};
/* Definitely not thread-safe... But we don't care :-) */
struct Exception *cur_ex_ptr = NULL;
#define try(in_ex) {\
(in_ex).code = 0;\
cur_ex_ptr = &(in_ex);\
} if (!setjmp((in_ex).jb))
#define catch(in_arg) else if (in_arg)
#define raise(in_code) {\
if (cur_ex_ptr != NULL) {\
cur_ex_ptr->code = in_code;\
jmp_buf *tmp = &cur_ex_ptr->jb;\
cur_ex_ptr = NULL;\
longjmp((*tmp), in_code);\
}\
}
void nested_func()
{
// Oops, this function raises an exception
raise(1);
}
int main(int argc, char **argv)
{
struct Exception ex;
try (ex) {
printf("Try Block 1\n");
} catch (ex.code > 0) {
printf("This is never seen\n");
}
try (ex) {
printf("Try Block 2\n");
nested_func();
} catch (ex.code > 0) {
printf("Exception Raised: %d\n", ex.code);
}
return 0;
}
@cleure
Copy link
Author

cleure commented Feb 4, 2014

To see the macros expanded, run (clang or gcc):

clang -E gistfile1.c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment