Skip to content

Instantly share code, notes, and snippets.

@dim13
Created August 9, 2019 12:28
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dim13/8700765914fba4048617e97a0118871e to your computer and use it in GitHub Desktop.
Save dim13/8700765914fba4048617e97a0118871e to your computer and use it in GitHub Desktop.
try/catch in plain c
#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