C++异常处理,错误
C++ exception handling, error
我正在使用一个库,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,它不会费心计算其第二个操作数。
相关文章:
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- Firebase C++VS2018 SDL2-在Firebase::app::create(..)上执行异常处理
- C++ 异常处理错误输出
- 错误 : 异常 : 引发未处理的异常: 读取访问冲突.0xDDDDDDDD临时温度
- C++执行期间的类成员函数错误/异常处理
- c ++ 如何在 while 循环中进行异常处理以拾取键入错误
- C++ 正则表达式错误(未处理的异常)
- CImg 错误未处理的异常堆栈溢出
- C++异常处理,错误
- 异常处理C++错误
- 从C‘goto’错误处理范式到C++异常处理范式的转换
- Android NDK 工具链异常处理 seg 错误
- Qt 与 opencv 异常处理错误
- 异常处理和从非致命错误中恢复
- c++中的异常处理从来没有捕捉到基本类型的异常,总是导致分段错误
- 如何为错误输入编写异常处理
- Crashlytics Fabric错误地处理了从32位平台上的swift ios调用的throw std::异常
- 使用异常处理库的(可能更改的)错误代码
- 文件处理错误(未处理异常)