Skip to content

Instantly share code, notes, and snippets.

@pr4v33n
Created March 7, 2011 16:59
Show Gist options
  • Save pr4v33n/858785 to your computer and use it in GitHub Desktop.
Save pr4v33n/858785 to your computer and use it in GitHub Desktop.
Exception handling in C
/* Author: http://twitter.com/jaz303 */
#include <stdio.h>
#include <setjmp.h>
#include <string.h>
#include <stdlib.h>
#define THROW(str) \
if (exception_count < 0) { \
fprintf(stderr, "unhandled exception '%s' at line %d in %s\n", str, __LINE__, __FILE__); \
exit(1); \
} \
exception_thrown = str; \
longjmp(exception_stack[exception_count--], 0)
#define THROW_AGAIN THROW(exception_thrown)
#define TRY \
{ \
int exception_status; \
if ((exception_status = setjmp(exception_stack[++exception_count])) == 0)
#define CATCH(str) else if (exception_status > 0 && strcmp(str, exception_thrown) == 0)
#define ENDTRY \
else { \
THROW_AGAIN; \
} \
} 0
jmp_buf exception_stack[50];
int exception_count = -1;
char* exception_thrown = NULL;
char* exception_to_throw;
int bar() {
THROW(exception_to_throw);
}
int foo() {
printf("IN foo()\n");
TRY {
bar();
} CATCH("foo") {
printf("caught a foo in foo()\n");
THROW_AGAIN;
} CATCH("bar") {
printf("caught a bar in foo()\n");
} ENDTRY;
printf("OUT foo()\n");
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: except exception_to_throw\n");
exit(1);
}
exception_to_throw = argv[1];
TRY {
foo();
} CATCH("foo") {
printf("caught a foo in main()\n");
} ENDTRY;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment