关于C++异常机制的笔记(SEH, try-catch)

昨天晚上加班解决了一个问题,是由于无法正确的捕获到异常导致的。刚开始用try-catch,但是没法捕获到异常;后面改成SEH异常才解决。因此今天将这个问题重新梳理了一遍,关于try-catch, SEH的基本知识,大家可以从MSDN(https://msdn.microsoft.com/en-us/library/4t3saedz(v=vs.100).aspx),或者自行查找亦可。 

关于二者之间的使用区别,做了些小小的测试,代码如下(OK-捕获异常、FAILED-未捕获异常):

void JsonTest()
{
    char szJson[] = "{\"val\":1}";
    Json::Reader reader;
    Json::Value root;
    if (false == reader.parse(szJson, root, false))
    {
        DEBUGA(DBG_DEBUG, "return false, JSON parse FAILED.");
        return ;
    }

    int val = root["val"].asInt();
    string val2 = root["val"].asString();
}

void StrTest()
{
    wstring strVal = L"a";
    strVal.at(10);
}

void NULLPtrTest()
{
    int* p = NULL;
    *p = 1;
}

void ZeroTest()
{
    int z = 0;
    double d = 100 / z;
    z = 100;
}

void OutRangeTest()
{
    char arr[] = "abc";
    char c = arr[5];
}

void TryCatchTest()
{
    try
    {
        JsonTest();        // OK
        StrTest();        // OK
        NULLPtrTest();    // FAILED
        ZeroTest();        // FAILED
        OutRangeTest();    // FAILED
    }
    catch (...)
    {
        MessageBox(0, L"try-catch", 0, 0);
    }
}

void SEHTest()
{
    __try
    {
        JsonTest();        // OK
        StrTest();        // OK
        NULLPtrTest();    // OK
        ZeroTest();        // OK
        OutRangeTest();    // FAILED
    }
    __except(EXCEPTION_EXECUTE_HANDLER)
    {
        MessageBox(0, L"SEH", 0, 0);
    }
}

int main()
{
    TryCatchTest();
    SEHTest();
    retrun 0;
}

 

posted @ 2016-01-06 16:52  nchxmoon  阅读(2861)  评论(0编辑  收藏  举报