开发者

How to catch the exception in initialization list? [duplicate]

开发者 https://www.devze.com 2022-12-22 17:21 出处:网络
This question already has answers here: Catching exceptions from a constructor's initializer list 开发者_StackOverflow(5 answers)
This question already has answers here: Catching exceptions from a constructor's initializer list 开发者_StackOverflow (5 answers) Closed 7 years ago.

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

}


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


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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号