I am trying to understand better the throw-catch mechanism when dealing with inheritance.
The problem I an trying to solve is the case of what will happens if while constructing the derived class the base class which is constructed first throws an exception.
#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);
}
After running my compiled code (g++ std=11) I get the following message:
Base throws an exception : test
terminate called after throwing an instance of 'std::runtime_error'
what(): test
Aborted (core dumped
My exception thrown by Base is caught by the try-catch of Derived constructor but for some reason the thrown exception does not stop there, why is that, and how to solve this?
And regardless I am open to suggestions if there is a better way to handle exception that may be thrown by base class when the derived is constructed.