【发布时间】:2020-08-07 10:00:32
【问题描述】:
在处理继承时,我试图更好地理解 throw-catch 机制。
我试图解决的问题是如果在构造派生类时首先构造的基类抛出异常会发生什么情况。
#include <stdexcept>
#include <iostream>
class Base
{
public:
Base()
{
throw std::runtime_error("test");
}
};
class Derived : public Base
{
public:
Derived() try : Base()
{
}
catch (std::runtime_error& e)
{
std::cout << "Base throws an exception : " << e.what() << std::endl;
}
};
int main ()
{
Derived temp;
return (0);
}
运行我的编译代码 (g++ std=11) 后,我收到以下消息:
Base 抛出异常:测试
在抛出 'std::runtime_error' 实例后调用终止
what(): 测试
中止(核心转储
我的 Base 抛出的异常被 Derived 构造函数的 try-catch 捕获,但由于某种原因抛出的异常并没有停止,这是为什么,以及如何解决这个问题?
不管我是否有更好的方法来处理在构造派生时基类可能抛出的异常,我都愿意接受建议。
【问题讨论】:
标签: c++ inheritance exception try-catch