Skip to content

Instantly share code, notes, and snippets.

@cleure
Created April 26, 2012 17:09

Revisions

  1. cleure revised this gist Apr 26, 2012. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions gistfile1.c
    Original file line number Diff line number Diff line change
    @@ -6,6 +6,7 @@ struct Exception {
    int code;
    };

    /* Definitely not thread-safe... But we don't care :-) */
    struct Exception *cur_ex_ptr = NULL;

    #define try(in_ex) {\
  2. cleure revised this gist Apr 26, 2012. 1 changed file with 9 additions and 7 deletions.
    16 changes: 9 additions & 7 deletions gistfile1.c
    Original file line number Diff line number Diff line change
    @@ -13,13 +13,15 @@ struct Exception *cur_ex_ptr = NULL;
    cur_ex_ptr = &(in_ex);\
    } if (!setjmp((in_ex).jb))

    #define catch else
    #define catch(in_arg) else if (in_arg)

    #define raise(in_code) {\
    cur_ex_ptr->code = in_code;\
    jmp_buf *tmp = &cur_ex_ptr->jb;\
    cur_ex_ptr = NULL;\
    longjmp((*tmp), 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()
    @@ -34,14 +36,14 @@ int main(int argc, char **argv)

    try (ex) {
    printf("Try Block 1\n");
    } catch {
    } catch (ex.code > 0) {
    printf("This is never seen\n");
    }

    try (ex) {
    printf("Try Block 2\n");
    nested_func();
    } catch {
    } catch (ex.code > 0) {
    printf("Exception Raised: %d\n", ex.code);
    }

  3. cleure created this gist Apr 26, 2012.
    49 changes: 49 additions & 0 deletions gistfile1.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    #include <stdio.h>
    #include <setjmp.h>

    struct Exception {
    jmp_buf jb;
    int code;
    };

    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 else

    #define raise(in_code) {\
    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 {
    printf("This is never seen\n");
    }

    try (ex) {
    printf("Try Block 2\n");
    nested_func();
    } catch {
    printf("Exception Raised: %d\n", ex.code);
    }

    return 0;
    }