I’m having a little trouble with making the following piece of code work. I cannot write a throw exception so I don’t know what else could I do.
case 't': // Top of Stack
try
{
cout << "Top() -- " << sPtr->Top() << endl; //this should run if the stack is not empty.
}
catch (StackEmpty)
{
cout << "Top() -- Failed Empty Stack" << endl; // this should run if the stack is empty.
}
break;
the sPtr points to Top() Function in a Class name Stack here is the code for that function:
int Stack::Top() const // Returns value of top integer on stack WITHOUT modifying the stack
{ cout << "*Top Start" << endl;
if(!IsEmpty())
return topPtr->data;
cout << "*Top End" << endl;
}
if I remove the if statement it causes a segmentation fault problem.
You’re not actually throwing anything on failure, and in the case when the stack is empty you’re just running off the end of the function without returning anything. Also your final log statement is only hit when the stack is empty.
You need something more like this: