1

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..

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
user1739398
  • 340
  • 2
  • 4
  • 10

3 Answers3

5

You should check if the iterator is pointing to nullptr.

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

EDIT

If you want an excpetion to be thrown if you ecounter a nullptr then you can use

for (vector<Test*>::iterator iter = lst.begin(); iter != lst.end(); iter++)
{
    if (*iter == nullptr)
        throw some_type_of_excpetion;
    (*iter)->Say();
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • This is OK in general but I'd prefer throwing an explicit exception if *iter == nullptr*. I've seen code that merrily continued on its way because a diligent programmer had guarded all errors *without* ever throwing, so it was very hard to find bugs! – Robinson Oct 26 '15 at 14:51
  • 1
    @Robinson I updated the answer to show how you would do that. – NathanOliver Oct 26 '15 at 14:53
4

C++ doesn't throw exceptions if you dereference null pointer in comparison to languages like Java. You have to explicitly check for null pointers.

Stas
  • 11,571
  • 9
  • 40
  • 58
4

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();
}
David Haim
  • 25,446
  • 3
  • 44
  • 78