【问题标题】:Exception does not get caught异常不会被捕获
【发布时间】:2012-06-16 10:56:08
【问题描述】:

我有一个基础异常和一个派生异常,存储的公共内部类:

//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;
}

派生类应该被捕获,但我不断收到错误“未处理的异常”。任何想法为什么?谢谢!

【问题讨论】:

    标签: c++ exception


    【解决方案1】:

    原因是AddProdException不是ProductException,因为你使用的是私有继承:

    class AddProdException: ProductException {};
    

    你需要使用公共继承:

    class AddProdException: public ProductException {};
    

    这同样适用于ProductExceptionexception,假设后者是std::exception

    【讨论】:

      【解决方案2】:

      如果没有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();
      };
      

      另外,还要在ProductException 中公开地从std::exception 继承,否则您将无法捕获std::exceptions(或者甚至更好,从std::runtime_error)。

      【讨论】:

        猜你喜欢
        • 2010-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多