Skip to content

Instantly share code, notes, and snippets.

@porglezomp
Last active May 26, 2022 20:43
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save porglezomp/634dedcf89dc32ed32af07b7c163ae81 to your computer and use it in GitHub Desktop.
Save porglezomp/634dedcf89dc32ed32af07b7c163ae81 to your computer and use it in GitHub Desktop.
Exception handling in C with setjmp and longjmp!
#include <iso646.h>
#include <setjmp.h>
#include <stdio.h>
// Exception Macros
int _exn_handler_idx = 0;
jmp_buf _exn_handlers[1024];
#define TRY(E) { int E; _exn_handler_idx += 1; \
if (not (E = setjmp(_exn_handlers[_exn_handler_idx])))
#define CATCH else
#define END_TRY _exn_handler_idx -= 1; }
#define THROW(E) longjmp(_exn_handlers[_exn_handler_idx], (E))
// Exception Definitions
#define DIV_BY_ZERO_EXN 1
// Demo Code
int divide(int num, int denom) {
if (denom == 0) {
THROW(DIV_BY_ZERO_EXN);
}
return num / denom;
}
int main() {
TRY(exception) {
printf("%d\n", divide(1, 0));
} CATCH {
switch (exception) {
case DIV_BY_ZERO_EXN:
printf("Division by zero\n");
return 1;
}
} END_TRY
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment