C++异常捕获

编程入门 行业动态 更新时间:2024-10-12 22:32:08

C++<a href=https://www.elefans.com/category/jswz/34/1771210.html style=异常捕获"/>

C++异常捕获

C++异常捕获

windows下使用_set_se_translator,linux下使用sjlj

  • main.cpp
#include <stdio.h>   // printf
#include "myException.h"int main()
{try{MY_EXCEPTION_CHECK// 0xc0000005int *p = 0;*p = 1;// 0xc0000094// int x=0;// int y=0;// volatile int z=x/y;}catch (const MyException &e){printf("myException %s\n", e.what());}catch (...){printf("exception...\n");}
}
  • myException.h
#ifndef _MY_EXCEPTION_H
#define _MY_EXCEPTION_H#ifdef _WIN32
#include <windows.h> // EXCEPTION_POINTERS
#include <eh.h>      // _set_se_translator
#else
#include <setjmp.h> // jmp_buf sigsetjmp
#endif#include <exception> // std::exception
#include <stdio.h>   // sprintf#if _WIN32
class MyException : public std::exception
{
public:MyException(int code) noexcept;const char *what() const throw();private:static void handler(unsigned int u, EXCEPTION_POINTERS *e);private:int m_code;
};
#else
class MyException : public std::exception
{
public:MyException(int code) noexcept;const char *what() const throw();private:static void handler(int code);private:int m_code;
};
#endif#if _WIN32
#define MY_EXCEPTION_CHECK
#else
extern jmp_buf env;#define MY_EXCEPTION_CHECK           \{                                \int ret = sigsetjmp(env, 1); \if (0 != ret)                \{                            \throw MyException(ret);  \}                            \}
#endif#endif // _MY_EXCEPTION_H
  • myException.cpp
#include "myException.h"#if _WIN32
#else
#include <signal.h> // signal
#endif#if _WIN32
MyException::MyException(int code) noexcept: m_code(code)
{_set_se_translator(MyException::handler); // need /EHa
}const char *MyException::what() const throw()
{static char str[50];sprintf(str, "C++ Exception. code: %x", m_code);return str;
}void MyException::handler(unsigned int u, EXCEPTION_POINTERS *e)
{throw MyException(u);
}
#else
jmp_buf env;
MyException::MyException(int code) noexcept: m_code(code)
{signal(SIGSEGV, MyException::handler); // segmentation faultsignal(SIGFPE, MyException::handler);  // divide by zero
}const char *MyException::what() const throw()
{static char str[50];sprintf(str, "C++ Exception. code: %d", m_code);return str;
}void MyException::handler(int code)
{siglongjmp(env, code);
}
#endifMyException myException(0);
  • CMakeLists.txt
cmake_minimum_required (VERSION 2.8.12)project (main)if(WIN32)# windows _set_se_translator need /EHaset(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /GS /EHa")
endif()include_directories(.)add_executable(${PROJECT_NAME} main.cpp myException.cpp)

更多推荐

C++异常捕获

本文发布于:2023-12-03 19:32:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1656992.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!