简体   繁体   English

如何在 C++ 中捕获基本 class 构造函数的异常?

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

I have a class that is derived from another class.我有一个从另一个 class 派生的 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 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++.但由于没有 C# 的base这样的关键字,我不知道在 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这里有一个很好的例子: Exception is catched in a constructor try block, and handling, but still gets rethrow the 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.最终,如果您设法在派生的 class 中捕获异常,您唯一应该做的就是重新抛出该异常或抛出一个新异常。 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.这是因为如果基础 class 构造函数未完成,则派生的 class 将位于未定义的 state 中,您不应使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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