【问题标题】:C++ Try Catch ThrowC++ 尝试 Catch Throw
【发布时间】:2013-11-10 21:37:40
【问题描述】:

每当我在堆栈为空时尝试将数字相加时,我都会尝试在堆栈程序中引发错误。在我的堆栈类的顶级函数中,我会抛出一个异常,以防堆栈上没有任何东西。然后我继续在我的主程序中创建一个 try and catch 块来捕获错误并显示一条消息。但是,我收到下面列出的错误,我不知道如何解决它。

错误:

terminate called after throwing an instance of 'char const*'

类Top():

 const T& top() const throw (std::string){
                    if(m_next != NULL){
                            return m_data;
                    }
                    else{
                            throw("Nothing on the Stack");
                    }
            };

int main():

int main(){
    string op;
    RobotCalc<int>* stack = new RobotCalc<int>;
    int operand1;
    int operand2;


    cin >> op;
    while(op != "@"){
            if(op == "+"){
                    try{
                    operand1 = stack->top();
                    stack->pop();
                    operand2 = stack->top();
                    stack->pop();
                    stack->push(operand1 + operand2);
                    }
                    catch (string e){
                            cout << e;
                    }
            }

代码还有更多内容,但这就是问题所在。类函数有 2 个成员变量:T 类型的 m_data(在本例中为 int)和指向下一个 RobotClass(堆栈成员)的指针。这是堆栈的链表版本。

【问题讨论】:

    标签: c++ exception-handling linked-list stack


    【解决方案1】:

    您正在捕获string 类型的消息,而 throw 正在抛出 const char*。抓住const char* 或者只是放一个“。

    【讨论】:

      【解决方案2】:

      我同意史蒂夫的观点。但是,您应该捕获异常,然后是错误消息而不是字符串。例如:

        catch (exceptionName e) {
           //catch block
        }
      

      c++ standard exceptions

      【讨论】:

        【解决方案3】:

        throw/catch 不对抛出的对象进行转换。如果你抛出const char*,那么你需要抓住const char*,而不是std::string

        错误消息告诉您有一个未捕获的异常。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-06-04
          • 2010-11-23
          • 2010-12-14
          • 2011-07-05
          • 1970-01-01
          • 1970-01-01
          • 2012-05-22
          相关资源
          最近更新 更多