#include <windows.h>
// 释放数组内存
#define FreeArray(pArray) { \
delete[] pArray; \
pArray = NULL; \
}
DWORD FilterFunction(int i = 1)
{
printf("%d ", i); // printed first
return EXCEPTION_EXECUTE_HANDLER;
}
void TryCatchFirst()
{
char* Test = NULL;
__try
{
__try
{
// 这个API是手动设置异常代码(这么称呼有点别扭)
RaiseException(1, // exception code
0, // continuable exception
0, NULL); // no arguments
}
__finally
{
printf("2 "); // this is printed second
}
}
__except ( FilterFunction() )
{
printf("3 \n"); // this is printed last
}
puts("One");
}
void TryCatchSecond()
{
char* Test = NULL;
__try
{
__try
{
Test = new char[2];
FreeArray(Test);
*(Test + 4096 ) = '\0';
// 此处数字一定要大,否则不能产生异常。
// 因为Windows平台下,new N个字节,系统分配的一定比N大。
// 4096大小刚好是一个页面大小,如果N>4096,那就自己扩大对应数字以产生异常
}
__finally
{
if (NULL != Test)
{
FreeArray(Test);
}
printf("2 "); // this is printed second
}
}
__except ( FilterFunction(GetExceptionCode()) )
{
printf("3 \n"); // this is printed last
}
puts("Second");
}
void TryCatchThree()
{
char* Test = NULL;
try
{
Test = new char[2];
FreeArray(Test);
*(Test + 4096 ) = '\0';
}
catch (...)
{
if (NULL != Test)
{
FreeArray(Test);
}
printf("4 \n");
}
puts("Three");
}
void TryCatchfourth()
{
char* Test = NULL;
try
{
Test = new char[2];
FreeArray(Test);
throw 0; // 这里我是随便抛出异常以测试
// 若没有手动throw,后面即使产生异常catch里面的代码还是不会被执行
puts("No "); // 接下来这两句不会被执行
*(Test + 4096 ) = '\0';
}
catch (...)
{
if (NULL != Test)
{
FreeArray(Test);
}
printf("4 \n");
}
puts("Fourth");
}
VOID main(VOID)
{
// TryCatchFirst();
// TryCatchSecond();
// TryCatchThree();
// TryCatchfourth();
}