c++ - 如何使我的异常处理机制可恢复?

标签 c++

#include <iostream>
#include <vector>

typedef std::vector<int> vector_int;
//My pop exception class!
class cPopOnEnpty{};
//My push exception class!
class cPushOnFull{};

class cStack
{
private:
    vector_int v;
    int m_top, m_cap;
public:
    cStack(int capacity):m_top(0),m_cap(capacity){}
    void pop()
    {
        if(m_top==0)
            throw cPopOnEnpty();
        v.erase(v.begin()+m_top);
        m_top--;
    }
    void push(int const& i)
    {
        if(m_top==m_cap)
            throw cPushOnFull();
        v.push_back(i); m_top++;
    }
};

int main(int argc, char **argv)
{
    cStack c(3);
    try {
        c.pop(); //m_top = 0 So exception should be thrown!
        c.push(2); //m_top = 1
        c.push(10); //m_top =2
        c.push(3);  //m_top =3
        c.push(19); //m_top = 4 Exception should be thrown here!
    }
    catch (cPopOnEnpty&)
    {
        std::cerr<< "Caught: Stack empty!"<<std::endl;
    }
    catch(cPushOnFull&)
    {
        std::cerr<<"Caught: Stack full!"<<std::endl;
    }
    return 0;
}

O/P - 捕获:堆栈为空!

所需的 O/P - 发现:堆栈空了! 捕获:堆栈已满!

在上面的代码中,我正在处理空 vector 上的弹出操作和满(容量受我限制) vector 上的推送。在这些情况下,当控件到达 main 的末尾并且程序退出时,我没有得到我想要的 o/p。我怎样才能使这个恢复,以便在处理一个调用的异常后它会转到下一个调用?

这里应该执行c.pop()之后的下一个语句。需要帮助!

最佳答案

为每个方法调用编写一个 Try/Catch block 。

try
{
    c.pop(); //m_top = 0 So exception should be thrown!
}
catch(cPopOnEnpty&)
{
    std::cerr<< "Caught: Stack empty!"<<std::endl;
}

关于c++ - 如何使我的异常处理机制可恢复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14987116/

相关文章:

c++ - 为什么在尝试编写图表时会出现段错误?

c++ - 为什么有专门为未初始化内存定义的 C++ 算法?

c++ - 获取 B 值错误 : Expression must have integral or unscoped enum type

c++ - 为什么模板实参用作另一个模板的模板参数时不能推导出来?

c++ - 动态类成员

c++ - 使用 devpartner 分析特定方法

c++ - 外部符号上的静态链接 OpenCV CUDA 应用程序错误

c++ - 函数坏指针运行时错误?

c++ - 从 RISC-V 裸机程序调用 printf 系统调用时使用 C++ 模拟器失败

C++ 简单指针传递