2013-02-20 54 views
2
#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 - 捉住:堆棧空!如何使我的異常處理mechansim恢復?

期望中的O/P - 捉住:堆棧空! 抓住:堆滿了!

在上面的代碼,我在處理空載體彈出和全推載體(容量是由我的限制)。這些情況下,我沒有得到我想要的o/p,因爲控制權到達主要結束並且程序退出。我怎樣才能使這個恢復,以便處理一個電話的異常後,它會進入下一個電話?

這裏c.pop()之後的下一個語句應該被執行。需要幫忙!

+0

注意:** eMpty **。 – 2013-02-20 18:32:16

回答

2

收件爲每個方法調用一個try/catch塊。

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

儘管醜陋,但這是C++允許的唯一方式。 – 2013-02-20 18:28:09

0

C++不允許,因爲堆棧已經展開(不像例如,Lisp的條件,是一個完全不同的野獸)的異常後恢復。

你將不得不架構代碼一些其他的方式,例如像@RobertHarvey建議。

0
try { 
     c.pop(); //m_top = 0 So exception should be thrown! 
    } 
    catch (cPopOnEnpty&) 
     { 
      std::cerr<< "Caught: Stack empty!"<<std::endl; 
     } 
    try{ 
     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(cPushOnFull&) 
    { 
     std::cerr<<"Caught: Stack full!"<<std::endl; 
    } 

問題解決!感謝你們! :D