Last active
May 26, 2022 20:43
-
-
Save porglezomp/634dedcf89dc32ed32af07b7c163ae81 to your computer and use it in GitHub Desktop.
Exception handling in C with setjmp and longjmp!
This file contains 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 <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