当列表中有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;
}
Run Code Online (Sandbox Code Playgroud)
此代码将生成"访问冲突读取"异常,并且无法捕获"try/catch".我尝试过使用"__try/__ except",但这只会给我以下编译错误:
C2712:不能在需要对象展开的函数中使用__try.
您应该检查迭代器是否指向nullptr.
for (vector<Test*>::iterator iter = lst.begin(); iter != lst.end(); iter++)
{
if (*iter != nullptr)
(*iter)->Say();
}
Run Code Online (Sandbox Code Playgroud)
编辑
如果你想要激活一个激励,nullptr那么你可以使用
for (vector<Test*>::iterator iter = lst.begin(); iter != lst.end(); iter++)
{
if (*iter == nullptr)
throw some_type_of_excpetion;
(*iter)->Say();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
605 次 |
| 最近记录: |