【发布时间】:2015-10-26 14:41:13
【问题描述】:
当列表中有NULL对象时如何处理异常?
#include <iostream>
#include <string>
#include <vector>
#include <exception>
#include <Windows.h>
using namespace std;
class Test {
public:
string m_say;
void Say() {
cout << m_say << endl;
}
Test(string say) {
m_say = say;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<Test*> lst;
Test * a = new Test("YO!");
lst.push_back(a);
lst.push_back(nullptr);
for (vector<Test*>::iterator iter = lst.begin(); iter != lst.end(); iter++)
{
try {
Test * t = *iter;
t->Say();
}
catch (exception& e) {
cout << e.what() << endl;
}
catch (...) {
cout << "Error" << endl;
}
}
return 0;
}
这段代码会产生“访问冲突读取”异常,无法用“try/catch”捕获。我试过使用“__try/__except”,但这只会给我以下编译错误:
C2712:不能在需要对象展开的函数中使用 __try..
【问题讨论】:
-
你为什么要推
nullptr? -
我正在寻找一个大项目中的错误,我怀疑问题可能是某个 NULL 以某种方式添加到列表中。