Windows下让C++程序捕获任何异常

Windows下让C++程序捕获任何异常

作者: kagula

时间: 2020-12-3

前言

        以前的一个windows C++项目被内存异常困扰, 过了十多年后, 抱着试试看的心情google了下, 发现Visual Studio 2019已经提供了Enable SEH的办法, 做了个小测试, 发现可以用!

早期catch SE(structured Exception) 会出现同步问题即SE是操作系统catch到而不是你进程catch到, 没进一步测试, 希望不会再有同步问题. 

正文

      首先需要在visual studio中启用SEH异常捕获, 具体写在代码注释里了, 下面贴代码.

// test by kagula
/*
* 为了捕获除零异常和内存存取异常enable SEH(Structured Exception Handling)
* 在Visual Studio中打开项目的属性页, 做如下设置
  C/C++->Code Generation -> Enable C++ Exception -> Yes with SEH Exceptions(/EHa)
  抱歉, 我一般能用英文版软件就用英文版,  不过相信同学们在中文版中也能找到相应的设置,  加油.
*/

#include <iostream>
#include <string>

using namespace std;

class A
{
	string abc = "read access violation demo";

public:
	void print()//this is the static member function!
	{
		cout << abc.c_str() << endl;
	}
};

int main()
{
	try
	{
		A* a = nullptr;
		cout << "following statement will trigger memory access violation" << endl;
		a->print();//for the abc member is not initialized, here will throw the read access violation exception.
		cout << "this line will never be invoke!" << endl;
	}
	catch (const std::exception& e)
	{
		cout << e.what() << endl;
	}
	catch (...)
	{
		cout << "abort" << endl;
	}

	cout << "finally..." << endl;
}

参考

[1]<<There is a very easy way to catch any kind of exception>>

  https://stackoverflow.com/questions/457577/catching-access-violation-exceptions

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kagula086

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值