2013-10-31 89 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