您的位置:首页 > 其它

测试 __try, __finally, __except

2015-12-30 23:45 295 查看
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");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: