Search code examples
c++error-handlingthrow

c++ throwing error


I am writing a c++ code that add o node to end of a list I want to throw error when a node is already exist, it is working but whenever I call it with already exiting node I get this error. Anyone know the reason and how it is fixed?

exception terminate called after throwing an instance of 'Error'
Aborted

List& List::addnode(node p){
    node *Current=NULL;

    p.nextNode = NULL;
    p.previousNode = NULL;

    if (!firstNode) firstNode = &p;

    else Current = firstNode;
    while (Current){
            if ((*Current) == p){
                    throw NodeExist;
                    return *this;
            }
            if (!(Current->nextNode)){
                    Current->nextNode = &p;
                    p.previousNode = Current;
                    return *this;
            }
            Current = Current->nextNode;

    }

}

edit: I call it like that

try{
x.addNode(p);
x.addNode(p1);
x.addNode(p2);
x.addNode(p1);
x.addNode(p4);
}
catch(int i){
cout<<i<<endl;
}

if I erase one of the x.addNode(p1); line it work normally without an exception...


Solution

  • you don't catch and handle NodeExist anywhere. so it goes up the call chain all the way to main.

    catch(int i) doesn't match NodeExist to catch that you need catch(Error e)