Created
April 26, 2012 17:09
-
-
Save cleure/2501036 to your computer and use it in GitHub Desktop.
Primitive try/catch Exception Handling in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To see the macros expanded, run (clang or gcc):
clang -E gistfile1.c