小编p3t*_*3t3的帖子

异常在构造函数 try 块中捕获并处理,但仍会再次重新抛出

我试图更好地理解处理继承时的抛出-捕获机制。

我试图解决的问题是,如果在构造派生类时,首先构造的基类抛出异常,将会发生什么情况。

#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);
}
Run Code Online (Sandbox Code Playgroud)

运行编译后的代码 (g++ std=11) 后,我收到以下消息:

基类抛出异常:测试

抛出“std::runtime_error”实例后调用终止

什么():测试

已中止(核心转储

我的 Base 抛出的异常被 Derived 构造函数的 try-catch 捕获,但由于某种原因,抛出的异常并没有停止在那里,为什么会这样,以及如何解决这个问题?

不管怎样,如果有更好的方法来处理派生类构造时基类可能抛出的异常,我愿意接受建议。

c++ inheritance exception try-catch

5
推荐指数
1
解决办法
503
查看次数

标签 统计

c++ ×1

exception ×1

inheritance ×1

try-catch ×1