vs C++如何捕获除0的异常

1.版本

vs2013

2.捕获除0异常

2.1.__try __except v1

#include <excpt.h>  
int _tmain(int argc, _TCHAR* argv[])
{

	__try{
		int a = 0;
		int b = 2 / a;
		cout << "b=" << b << endl;
	}
	__except (EXCEPTION_EXECUTE_HANDLER){
		unsigned long code=GetExceptionCode();
		cout << "exception code=" <<code<< endl;
	}
}

输出如下:
在这里插入图片描述

2.2.__try __except v2

#include <windows.h>


int filter(unsigned int code, _EXCEPTION_POINTERS   *ep)   {
	if (code == EXCEPTION_INT_DIVIDE_BY_ZERO)   {
		return EXCEPTION_EXECUTE_HANDLER;//对异常进行处理

	}
	else{
		return  EXCEPTION_CONTINUE_SEARCH;//交由下一个try处理
	};

}


int _tmain(int argc, _TCHAR* argv[])
{
	__try{
		int a = 0;
		int b = 2 / a;
		cout << "b=" << b << endl;
	}
	__except (filter(GetExceptionCode(), GetExceptionInformation())){
		cout << "exception" << endl;
	}
}

这种比较灵活,可以在filter里判断具体的结构化异常类型,以决定是否要处理。

2.3.try throw catch

int _tmain(int argc, _TCHAR* argv[])
{
	try{
		int a = 0;
		int b = 2 / a;
		cout << "b=" << b << endl;
	}
	catch (...){
		cout << "exception" << endl;
	}
}

还要设置下项目属性:
在这里插入图片描述
这种的确定是没法确定具体的结构化异常类型。

2.4._set_se_translator

由于在一个作用域内同时使用__try和try会报错,原因看这里:
_set_se_translator 用法 + C++异常与windows异常
可以通过_set_se_translator解决这个问题,把结构化异常转换为C++异常,这样就只需要用try就可以了。

#include <cassert>
#include <windows.h>
class CSEHException
{
public:
	CSEHException(UINT code, PEXCEPTION_POINTERS pep)
	{
		m_exceptionCode = code;
		m_exceptionRecord = *pep->ExceptionRecord;
		m_context = *pep->ContextRecord;
		assert(m_exceptionCode == m_exceptionRecord.ExceptionCode);
	}
	operator unsigned int() { return m_exceptionCode; }

	UINT m_exceptionCode;
	EXCEPTION_RECORD   m_exceptionRecord;
	CONTEXT   m_context;
};

// 结构化异常到C++异常转化器
void cdecl TranslateSEHtoCE(UINT code, EXCEPTION_POINTERS *pep)
{
	throw CSEHException(code, pep);
}
int _tmain(int argc,
 _TCHAR* argv[])
{
	_set_se_translator(TranslateSEHtoCE);

	try
	{
		int a = 0;
		int b = 2 / a;
		cout << "b=" << b << endl;
	}
	catch (CSEHException e)
	{
		cout << "exception code=" << e.m_exceptionCode<<endl;
	}
}

同时还要设置项目属性:
在这里插入图片描述
输出:
在这里插入图片描述
异常转化器在每个线程的基础上进行工作,因此你需要为每一个线程安装一个转化器。

参考文章:
1._set_se_translator 用法 + C++异常与windows异常
2._set_se_translator

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值