I have to use stacks for my program, but I've never done them before so I looked up a code in my book to try and help me understand it but parts are confusing me.

void push(char item)
          { if (full())
               throw FullStack();
                { NodeType* location;
                  location = new NodeType;
                  location->item = item;
                  location->next = ptr;
                  ptr = location;
           } // END OF PUSH

     void pop()
          { if (empty())
               throw EmptyStack();
                { NodeType* temp;
                  temp = ptr;
                  ptr = ptr->next;
                  delete temp;

     char top()
          { if (empty())
            throw EmptyStack();
            else return ptr->item;

I get all the else statements, I don't get what this "throw EmptyStack()"/"throw FullStack()" thing does, and my book doesn't explain it. Can someone explain what that means and how it's suppose to be helpful?

The whole reason I'm asking is that I'm using a stack to keep track of decisions a person has made, and if they pop out all their decisions, they can't go back any more. Well, my previous if statement was

if (a.top == NULL) cout << "B) Back";

Thus telling the user they can go back if there is a choice or not if there isn't. Well, this "throw EmptyStack();" thing in my top function messes with that statement so I don't know what to do to change it so it works. Is the throw really needed or can I get rid of it in the top(), push(), and pop() functions?

>>Is the throw really needed

No. It is one way to try to handle errors gracefully. You can write functional stacks without using throw (and the associated try/catch) statements.

If you want to learn a little something about try/catch/throw and how it can be used to handle errors/exceptions then the appropriate section in the following link seemed pretty readable.


Alright. Thank you. That helped a lot.