Search code examples
c++seh

Handle access violation exception in vector iteration


How can I handle the exception when there is a NULL object in the list?

#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;
}

This code will generate an "access violation reading" exception, and it is not possible to catch with "try/catch". I've tried using "__try/__except" but that only gives me the following compilation error:

C2712: Cannot use __try in functions that require object unwinding..


Solution

  • Well... you could build your project with /EHa flag. it might convert Win32 exceptions into regular C++ exceptions. then you can catch these execeptions with

    catch(...){}
    

    But
    you shouldn't need to rely on such hackish ways to replace regular - proven ways to deal with memory exceptions - don't create them at first place!

    your problem is easlily solved with regular null check.

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