C++异常处理,错误

C++ exception handling, error

本文关键字:错误 异常处理 C++      更新时间:2023-10-16

我正在使用一个库,RapidXML,但我的问题更普遍。该库像现在item->first_node("CRAP")->first_node("CRAP")一样解析 xml,如果我把它放在 if 语句中,它会崩溃。如果我这样说:item->first_node("CRAP")它不会。

我是C++初学者,我对异常了解不多,但是:

try
{
    if(item->first_node("CRAP")->first_node("CRAP"))
    {
    }
    cout << "OK";
} catch (...)
{
    cout << "CRASH";
}

以上崩溃。如何检查我的节点是否存在而不会崩溃(并且不会逐个循环所有项目)?

你只需要一步一步来:

if (item != 0) // check if item is null
{
    rapidxml::xml_node<char>* node = item->first_node("CRAP"); // Try to grab first child node
    if (node != 0)
    {
        // okay got a valid node, grab next one
        rapidxml::xml_node<char>* next = node->first_node("CRAP");
        if (next != 0)
        {
           // Okay
        }
    }
}

当您一步尝试时,即 item->first_node("CRAP")->first_node("CRAP"),你永远不会检查对first_node的第一次调用是否返回了空指针(假设item也是有效的指针)。

听起来item要么是空的,要么item->first_node("CRAP")返回 NULL。 试试这个,看看你得到什么输出:

try
{
    node *n; // <-- use whatever type first_node() actually returns
    if (!item)
        cout << "item is NULL";
    else
    {
        n = item->first_node("CRAP");
        if (!n)
            cout << "first node is NULL";
        else
        {
            n = n->first_node("CRAP");
            if (!n)
                cout << "second node is NULL";
            else
                cout << "OK";
        }
    }
}
catch (...)
{
    cout << "CRASH";
}

在将表达式用作较长表达式的一部分之前,请始终测试表达式是否NULL。永远不要写这样的东西

if(item->first_node("CRAP")->first_node("CRAP"))

如果first_node("CRAP")可以返回NULL.相反,写一些类似的东西

if(item->first_node("CRAP") && item->first_node("CRAP")->first_node("CRAP"))

这是因为 '&&'(逻辑和)运算符使用惰性求值:如果第一个操作数的计算结果为 false,它不会费心计算其第二个操作数。