不能从派生类抛出基类异常

Cant throw base class exception from dervied class

本文关键字:基类 异常 派生 不能      更新时间:2023-10-16

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

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

我在网上搜索了一下,似乎派生类违反了基类中的契约。

我的疑问是基类为派生类对象做了一个契约,然而,我正在使用基类,所以契约在哪里被打破了。

问题就在这里:

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

void Derived::f() throw(BaseException) 

您基本上承诺anyBase.f将抛出DerivedException(更专门化)异常。然后在你的Derived class中,你试图"放松"这个承诺,告诉你会抛出一个更通用的BaseException。当你从一个类中派生另一个类时,你不能这样做。将第一个更改为throw(BaseException)或将第二个更改为throw(DerivedException)。您甚至可以两者都做,因为这样Derived类将限制Base类所做的合约,并且是允许的。