Created
August 9, 2019 12:28
-
-
Save dim13/8700765914fba4048617e97a0118871e to your computer and use it in GitHub Desktop.
try/catch in plain c
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 <err.h> | |
#include <stdio.h> | |
#include <setjmp.h> | |
#include <signal.h> | |
static sigjmp_buf exception; | |
#define try if (!sigsetjmp(exception, 1)) | |
#define catch else | |
#define throw siglongjmp(exception, 1) | |
void | |
handler(int sig) | |
{ | |
throw; | |
} | |
void | |
init_try(void) | |
{ | |
struct sigaction sa; | |
sigemptyset(&sa.sa_mask); | |
sa.sa_flags = 0; | |
sa.sa_handler = handler; | |
sigaction(SIGFPE, &sa, NULL); | |
sigaction(SIGSEGV, &sa, NULL); | |
} | |
int | |
main() | |
{ | |
int n = 0; | |
init_try(); | |
try | |
printf("%d\n", 1 / n); | |
catch | |
warnx("Look Ma, I divided by zero!"); | |
try | |
((void (*)(void))NULL)(); | |
catch | |
warnx("SIGSEGV you say? Well..."); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment