Search code examples
c++exceptionconstructorrethrow

How to catch a base class constructor's exception in C++?


I have a class that is derived from another class. I want to be able to catch and re-throw the exception(s) thrown by the derived class's constructor in my derived class's constructor.

There seems to be a solution for this in C#: https://stackoverflow.com/a/18795956/13147242

But since there is no such keyword as C#'s baseI have no idea how and if this is possible in C++.

Is there a solution? This would enable me to reuse quite a lot of code.


Solution

  • There is a pretty good example of this here: Exception is caught in a constructor try block, and handled, but still gets rethrown a second time

    Ultimately, if you manage to catch an exception in the derived class the only thing you should do is to either rethrow that exception or throw a new one. This is because if the base class constructor does not complete then the derived class will be in an undefined state and you should not use it.