以下摘自《Windows核心編程》,不做過多說明直接看代碼吧。
#include "stdafx.h"
#include <Windows.h>
using namespace std;
class Exception
...{
public:
static void MapSEtoCE(void ) ...{_set_se_translator(TranslateSEtoCE); }
Operator DWord() ...{ return er.ExceptionCode; }
private:
Exception(PEXCEPTION_POINTERS pep)
...{
er = *pep->ExceptionRecord;
tx = *pep->ContextRecord;
}
static void _cdecl TranslateSEtoCE(UINT dwEC, PEXCEPTION_POINTERS pep)
...{
throw Exception(pep );
}
private:
EXCEPTION_RECORD er;
CONTEXT tx;
};
int _tmain(int argc, _TCHAR* argv[])
...{
Exception::MapSEtoCE();
try...{
*(byte*)0 = 0; // Access violation
int x = 0;
x = 5 / x; // Division by zero
}
catch(Exception se)
...{
switch(se)
...{
case EXCEPTION_Access_VIOLATION:
...{
cout << "Access Violation" << endl;
}
break;
case EXCEPTION_INT_DIVIDE_BY_ZERO:
...{
cout << "Division by zero" << endl;
}
break;
default:
...{
cout << "Error code:" << se << " Unknown exception" << endl;
}
break;
}
}
return 0;
}
應該可以捕獲所有異常。包括已知的、未知的和無法預料的。
需要在setting中c/c++=> project option中添加 /EHa .否則.release時會初VC++優化掉