【问题标题】:Handle access violation exception in vector iteration处理向量迭代中的访问冲突异常
【发布时间】: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 以某种方式添加到列表中。

标签: c++ seh


【解决方案1】:

您应该检查迭代器是否指向nullptr

for (vector<Test*>::iterator iter = lst.begin(); iter != lst.end(); iter++)
{
    if (*iter != nullptr)
        (*iter)->Say();
}

编辑

如果你想在遇到nullptr 时抛出异常,那么你可以使用

for (vector<Test*>::iterator iter = lst.begin(); iter != lst.end(); iter++)
{
    if (*iter == nullptr)
        throw some_type_of_excpetion;
    (*iter)->Say();
}

【讨论】:

  • 这通常是可以的,但如果 iter == nullptr,我更愿意抛出一个明确的异常。我已经看到代码在它的过程中愉快地继续下去,因为勤奋的程序员已经保护了所有错误没有抛出,所以很难找到错误!
  • @Robinson 我更新了答案以显示您将如何做到这一点。
【解决方案2】:

嗯...您可以使用/EHa 标志构建您的项目。它可能将 Win32 异常转换为常规 C++ 异常。那么您可以使用

捕获这些异常
catch(...){}

但是
你不应该依赖这种骇人听闻的方法来替换常规的——经过验证的处理内存异常的方法——首先不要创建它们!

您的问题可以通过定期的空检查轻松解决。

if (t){
  t->Say();
}

【讨论】:

    【解决方案3】:

    与 Java 等语言相比,如果您取消引用空指针,C++ 不会引发异常。您必须明确检查空指针。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-24
      • 2011-04-12
      • 2015-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多