2012-06-16 41 views
1

我有一個底座和一個派生的異常,公衆內部類店:異常不會被逮住

//base class - ProductException 
    class ProductException: exception 
    { 
    protected: 
     const int prodNum; 
    public: 
     //default+input constructor 
     ProductException(const int& inputNum=0); 
     //destructor 
     ~ProductException(); 
     virtual const char* what() const throw(); 
    }; 

    //derived class - AddProdException 
    class AddProdException: ProductException 
    { 
    public: 
     //default+input constructor 
     AddProdException(const int& inputNum=0); 
     //destructor 
     ~AddProdException(); 
     //override base exception's method 
     virtual const char* what() const throw(); 
    }; 

此功能,將引發派生的異常:

void addProduct(const int& num,const string& name) throw(AddProdException); 
void Store::addProduct(const int& num,const string& name) 
{ 
    //irrelevant code... 
    throw(AddProdException(num)); 
} 

和調用一個函數函數並試圖捕獲一個異常:

try 
{ 
    switch(op) 
    { 
     case 1: 
     { 
      cin>>num>>name; 
      st.addProduct(num,name); 
      break; 
     } 
    } 
} 
... 
catch(Store::ProductException& e) 
{ 
    const char* errStr=e.what(); 
    cout<<errStr; 
    delete[] errStr; 
} 

派生類應該被捕獲,但是我k eep得到錯誤「未處理的異常」。任何想法爲什麼?謝謝!

回答

4

的原因是,AddProdException不是ProductException,因爲你正在使用私有繼承:

class AddProdException: ProductException {}; 

您需要使用公有繼承:

class AddProdException: public ProductException {}; 

這同樣適用於ProductExceptionexception,假設後者是std::exception

+0

這麼愚蠢的錯誤。謝謝! – nodwj

4

沒有public關鍵字,默認情況下,繼承被認爲是private。這意味着AddProdException不是ProductException。使用公有繼承,像這樣:

class AddProdException : public ProductException 
{ 
public: 
    //default+input constructor 
    AddProdException(const int& inputNum=0); 
    //destructor 
    ~AddProdException(); 
    //override base exception's method 
    virtual const char* what() const throw(); 
}; 

此外,從std::exception繼承公開在ProductException爲好,否則你將無法趕上std::exception小號兩種(甚至更好,從std::runtime_error)。