Skip to content

Instantly share code, notes, and snippets.

@kaiix
Created September 23, 2016 09:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaiix/965ed6ed0cfb23b1d61e9f92b0c9b9cd to your computer and use it in GitHub Desktop.
Save kaiix/965ed6ed0cfb23b1d61e9f92b0c9b9cd to your computer and use it in GitHub Desktop.
try/catch with setjmp
#include <unistd.h>
#include <stdio.h>
#include <setjmp.h>
#include <signal.h>
jmp_buf j;
void try()
{
printf("call try\n");
while (1) {
sleep(5);
printf("throw exception\n");
int exception_no = 2;
longjmp(j, exception_no);
}
}
void catch(exception_no)
{
printf("call catch\n");
printf("catch exception: %d\n", exception_no);
}
void finally()
{
printf("call finally\n");
}
void error_handler(int sig)
{
longjmp(j, 1);
}
int main()
{
int eno;
if ((eno = setjmp(j)) > 0) {
catch(eno);
} else {
signal(SIGINT, error_handler);
try();
}
finally();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment