#include <signal.h>#include <iostream>class e_access_violation{ public: e_access_violation() {};};void segv_handler(int sig){ throw e_access_violation();}int main(){ signal(SIGSEGV, segv_handler); try { *((char *)0) = 0; } catch (e_access_violation) { std::cout << "Access Violation" << std::endl; } std::cout << "I'm live!" << std::endl; return 0;}
yurik@vpn ~$ g++ except.cppyurik@vpn ~$ ./a.outAccess ViolationI'm live!
#ifndef TRY_H#define TRY_H#include <setjmp.h>#include <csignal>void setup_signals(void);#ifndef IN_TRY_CCextern#endif sigjmp_buf buf;#define __try \ setup_signals(); \ int direct_ret = sigsetjmp(buf, 1); \ if (direct_ret) \#define __except else#define __finally#endif /* TRY_H */
#define IN_TRY_CC#include "try.h"void setup_signals(void){ std::signal(SIGHUP, signals_handler); std::signal(SIGINT, signals_handler); std::signal(SIGILL, signals_handler); std::signal(SIGBUS, signals_handler); std::signal(SIGFPE, signals_handler); std::signal(SIGSEGV, signals_handler);}void unset_signals(void){ std::signal(SIGHUP, SIG_DFL); std::signal(SIGINT, SIG_DFL); std::signal(SIGILL, SIG_DFL); std::signal(SIGBUS, SIG_DFL); std::signal(SIGFPE, SIG_DFL); std::signal(SIGSEGV, SIG_DFL);}void signals_handler(int signo){ unset_signals(); siglongjmp(buf, 1);}
#include <iostream>#include "try.h"int main(){ __try { *((char *)0) = 0; } __except { std::cout << "Access Violation" << std::endl; } std::cout << "I'm live!" << std::endl; // а вот после этой строчки приложение реально "свалится" *((char *)0) = 0; // и никакого возврата нуля не будет return 0;}
yurik@vox:~/work/exceptions$ ./a.outAccess ViolationI'm live!Segmentation fault