【问题标题】:try throw exception handling尝试抛出异常处理
【发布时间】:2011-11-23 06:35:32
【问题描述】:

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

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

【问题讨论】:

  • 在学习编写 C++ 代码时,检查每个 if 而不检查 else 并确保真的这是你想要的。

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


【解决方案1】:

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

你需要更多这样的东西:

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

【讨论】:

  • 完美!我可以发誓我至少尝试过两次,两种不同的方式,这给了我一个错误,但无论如何再次感谢。
【解决方案2】:

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

顺便说一下,异常是这样抛出的:

throw StackEmpty();

【讨论】:

    猜你喜欢
    • 2013-07-24
    • 2015-07-16
    • 2019-07-11
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    • 2018-06-02
    • 2023-03-06
    相关资源
    最近更新 更多