Created
September 23, 2016 09:08
-
-
Save kaiix/965ed6ed0cfb23b1d61e9f92b0c9b9cd to your computer and use it in GitHub Desktop.
try/catch with setjmp
This file contains hidden or 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 <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