如何捕获初始化列表中的异常?
我有一个关于如何捕获初始化列表中的异常的问题。
例如,我们有一个从 Bar 派生的类 Foo
class Foo {
public:
Foo(int i) {throw 0; }
}
class Bar : public Foo{
public:
Bar() : Foo(1) {}
}
I have a question about how to catch the exception in the initialization list.
For example, we have a class Foo derived from Bar
class Foo {
public:
Foo(int i) {throw 0; }
}
class Bar : public Foo{
public:
Bar() : Foo(1) {}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为语法类似于 this (尽管最好在调用者中捕获此类内容。并且一旦抓住了你会做什么?)
I think the syntax is like this (even though it's better to catch such things in the caller. And what are you going to do once you caught it?)
C++ 有这样做的机制,但很少使用。它是函数 try 块:
请参阅这个经典的 gotw,它概述了为什么它只能用于转换异常(例如,异常类型 FooException 变为 BarException)。
C++ has a mechanism for doing so, but it is rarely used. It is the function try block:
See this classic gotw, which outlines why it should only be used to translate exceptions (e.g., exception type FooException becomes BarException).
我相信这应该被创建对象的过程捕获。
I believe this should be caught by the procedure creating the object.
考虑用
替换麻烦的实例boost::可选
。然后您可以将其初始化推迟到构造函数的主体中。Consider replacing the troublesome instance with a
boost::optional
. Then you can defer its initialization into the body of the constructor.