How to catch the exception in initialization list?

2019-02-13 10:32发布

This question already has an answer here:

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) {}

}

4条回答
劳资没心,怎么记你
2楼-- · 2019-02-13 11:13

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?)

Bar::Bar()
try
  : Foo(1)
{
}
catch( const SomeException &e )
{
}
查看更多
叼着烟拽天下
3楼-- · 2019-02-13 11:20

Consider replacing the troublesome instance with a boost::optional. Then you can defer its initialization into the body of the constructor.

查看更多
戒情不戒烟
4楼-- · 2019-02-13 11:23

C++ has a mechanism for doing so, but it is rarely used. It is the function try block:

Bar::Bar()
try
  : Foo(1)
{
}
catch( Something )
{
}

See this classic gotw, which outlines why it should only be used to translate exceptions (e.g., exception type FooException becomes BarException).

查看更多
等我变得足够好
5楼-- · 2019-02-13 11:31

I believe this should be caught by the procedure creating the object.

查看更多
登录 后发表回答