Skip to content

Instantly share code, notes, and snippets.

@dim13 dim13/try.c
Created Aug 9, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.