#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/