无法从派生类中抛出基类异常

时间:2013-06-22 13:50:36

标签: c++ exception

我编写了一个代码,而不是抛出派生类异常,而是从派生类

中抛出基类异常
#include <iostream>
using namespace std;

class Base {
public:
  class BaseException {};
  class DerivedException : public BaseException {};
  virtual void f() throw(DerivedException) {
    throw DerivedException();
  }
  virtual void g() throw(BaseException) {
    throw BaseException();
  }
};

class Derived : public Base {
public:
  void f() throw (BaseException) 
  {
    throw BaseException();
  }
  virtual void g() throw (BaseException)
 {
    throw DerivedException();
  }
};

int main()
{
    Derived D;

    return 0;
}

http://codepad.org/xMdNAeVE

无法编译并说

Line 18: error: looser throw specifier for 'virtual void Derived::f() throw (Base::BaseException)'
compilation terminated due to -Wfatal-errors.

我在网上搜索,似乎派生类违反了基类中的合同。

我怀疑基类是否为派生类对象签订了合约,但是我使用的是基类,所以合同在哪里被破坏了。

1 个答案:

答案 0 :(得分:0)

问题在于:

virtual void Base::f() throw(DerivedException)

void Derived::f() throw(BaseException) 

你基本上承诺anyBase.f会抛出DerivedException(更专业)的例外。然后在你的Derived class中,你试图“放松”这个承诺,告诉你会抛出一个更通用的BaseException。当你从另一个派生一个类时,你不能这样做。将第一个更改为throw(BaseException)或将第二个更改为throw(DerivedException)。您甚至可以同时执行这两项操作,因为Derived类会{strong>限制 Base类合同,允许。< / p>