开发者

try throw exception handling

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 << "*To开发者_如何学编程p 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:

int Stack::Top() const  // Returns value of top integer on stack WITHOUT modifying the stack
{ 
  cout << "*Top Start" << endl;
  if(!IsEmpty())
  {
     cout << "*Top End" << endl;
     return topPtr->data;
  }
  cout << "*Top End" << endl;
  throw StackEmpty();
}


Why "can't" you throw an exception? Note that if you don't return anything from Top() (when your stack is empty) you are asking for trouble to happen. It should be a precondition to Top() that the stack is not empty, so if you can't throw an exception an assert would be acceptable, even preferable at least to me.

By the way, exceptions are thrown like this:

throw StackEmpty();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜