C++ try catch

标签 c++ exception linked-list stack

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

错误:

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

最佳答案

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

关于C++ try catch ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19697069/

相关文章:

c++ - 如何在 C++ 中打印已定义常量的内存地址

.net - 如何定位特定版本的 C++ 运行时?

c++ - 从文件中读取字符串并排序

java - TextToSpeech 抛出未知异常

c# - 减少 C# 上 MySQL 的超时异常

java - Go 的等价于 'throws' 的子句是什么?

c++ - STL 是否有办法在调用 less than 之前应用一个函数?

收集2 : fatal error:/usr/local/bin/gnm returned 1 exit status

c - fgetc 无法加载文件的最后一个字符

c - C中的段错误链表