Created
May 4, 2019 21:39
-
-
Save Jacajack/cdd614310959ce0ac8f6faa09a84d861 to your computer and use it in GitHub Desktop.
C setjmp/longjmp based exception system
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 <setjmp.h> | |
#include <stdio.h> | |
union exception_data | |
{ | |
const char *string; | |
double d; | |
int i; | |
}; | |
enum exception_type | |
{ | |
STRING, | |
DOUBLE, | |
INT | |
}; | |
struct exception_status | |
{ | |
union exception_data d; | |
enum exception_type t; | |
jmp_buf buf; | |
}; | |
void generic_throw( struct exception_status *ex ) | |
{ | |
longjmp( ex->buf, 1 ); | |
} | |
void throw_string( struct exception_status *ex, const char *str ) | |
{ | |
ex->d.string = str; | |
ex->t = STRING; | |
generic_throw( ex ); | |
} | |
void throw_int( struct exception_status *ex, int i ) | |
{ | |
ex->d.i = i; | |
ex->t = INT; | |
generic_throw( ex ); | |
} | |
void throw_double( struct exception_status *ex, double d ) | |
{ | |
ex->d.d = d; | |
ex->t = DOUBLE; | |
generic_throw( ex ); | |
} | |
void generic_catch( const struct exception_status *ex ) | |
{ | |
switch ( ex->t ) | |
{ | |
case STRING: | |
fprintf( stderr, "caught string: %s\n", ex->d.string ); | |
break; | |
case INT: | |
fprintf( stderr, "caught int: %d\n", ex->d.i ); | |
break; | |
case DOUBLE: | |
fprintf( stderr, "caught double: %f\n", ex->d.d ); | |
break; | |
default: | |
fprintf( stderr, "uncaught exception\n" ); | |
break; | |
} | |
} | |
#define generic_try(ex) (!setjmp((ex)->buf)) | |
struct exception_status EX; | |
int main( ) | |
{ | |
if ( generic_try( &EX ) ) | |
{ | |
//throw_string( &EX, "hahah" ); | |
throw_int( &EX, 78 ); | |
} | |
else | |
{ | |
generic_catch( &EX ); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment