尝试抛出异常处理

时间:2011-09-22 23:31:30

标签: c++ exception-handling segmentation-fault try-catch stack

我在使下面的代码工作时遇到了一些麻烦。我不能写一个抛出异常,所以我不知道还能做什么。

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;

sPtr指向类名称中的Top()函数这里是该函数的代码:

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语句,则会导致分段错误问题。

2 个答案:

答案 0 :(得分:3)

为什么“不能”你抛出异常?请注意,如果您没有从Top()返回任何内容(当您的堆栈为空时),您就会遇到麻烦。 Top()堆栈不是空的应该是一个先决条件,所以如果你不能抛出异常,断言是可以接受的,至少对我来说是可取的。

顺便说一下,异常会像这样抛出:

throw StackEmpty();

答案 1 :(得分:3)

你实际上并没有在失败时抛出任何东西,而在堆栈为空的情况下,你只是在函数结束时运行而不返回任何东西。此外,只有在堆栈为空时才会触发最终的日志语句。

你需要更像这样的东西:

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();
}