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

猜你喜欢

转载自blog.csdn.net/lee353086/article/details/110521502