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