简体   繁体   中英

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 base I 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM