不能从派生类抛出基类异常
Cant throw base class exception from dervied class
我写了一段代码,不是抛出派生类异常,而是从派生类抛出基类异常
#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
类所做的合约,并且是允许的。
相关文章:
- std::具有相同基类的类的变体
- 是否可以初始化不可复制类型的成员变量(或基类)
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 基类中的函数名称解析
- C++初始化基类
- 如何通过派生类函数更改基类中的向量
- 自定义异常中的用户定义的空构造函数,具有多个继承和抽象基类
- 从基类强制转换为派生类会引发异常
- 通过引用派生类对象从基类对象执行向下转换时引发bad_cast异常
- 基类catch不捕获异常,即使它出现在派生类catch之前
- 为什么当我抛出派生类的对象时,基类的 catch 块会捕获异常
- 处理C++中基类的重写方法的异常
- 为什么派生类异常可以被基类捕获子句捕获
- 不能从派生类抛出基类异常
- 对所有异常使用一个基类的缺点是什么?
- 如何在异常时不从构造函数调用基类析构函数
- 从其基类捕获的自己的异常类调用方法
- 在c++中,如果基类构造函数异常,则构造函数和析构函数的顺序可以是这样
- 作为抛出异常对象的结构基类
- c++基类中的异常处理