2013-10-31 93 views
0

我想在我的堆栈程序中抛出一个错误,只要我尝试在堆栈为空时一起添加数字。在我的堆栈类的顶层函数内部,如果堆栈中没有任何东西,我会引发异常。然后我继续在主程序中创建一个try和catch块来捕获错误并显示一条消息。但是,我收到下面列出的错误,我不知道如何解决它。C++ Try Catch Throw

错误:

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

级顶尖():

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

INT主要():

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(栈成员)的指针。这是一个堆栈的链接列表版本。

回答

1

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

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

1

您正在捕捉string类型的消息,而掷出const char*。抓住const char*或只是把”

0

我与史蒂夫同意然而,你应该捕捉异常,跟该错误消息,而不是一个字符串,例如:。

catch (exceptionName e) { 
    //catch block 
    } 

c++ standard exceptions