C语言标准是没有 try-catch语法 的, M$家自己提供了一组.
/// @file ClassroomExamples.c
/// @brief 验证C语言的非标准try, catch
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#include <crtdbg.h>
#include <conio.h>
void fnTest_TryCatchByM$();
int main(int argc, char *argv[ ], char *envp[ ])
{
fnTest_TryCatchByM$();
printf("END, press any key to quit\n");
getchar();
return 0;
}
void fnTest_TryCatchByM$()
{
int* p = 0x00000000; // pointer to NULL
puts("hello");
/// __try, __finally, __except都不是C标准函数, 是M$自己家的
/// 为了通用性, 还是不用__x函数
/// __try要有配对的__finally或__except, 只能配对一个
__try
{
puts("in try");
__try
{
puts("in try");
/// 如果不在__try中, 就C05了
*p = 13; // causes an access violation exception;
}
__finally
{
/// 被__finally捕获的异常, 还会被上一级的__except捕获
/// 反之不行(先被__except捕获, 不会再被上一级的__finally捕获)
puts("in finally");
}
}
/// 当异常发生时, 至少要被一个__except捕获, 否则C05
/// 进不了对应的__finally
/// 最外层的异常捕获必须是__except, 如果是__finally
/// 否则异常发生时, 会C05
__except(puts("in filter"), 1)
{
puts("in except");
}
puts("world");
}