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

独自空忆成欢 提交于 2019-11-30 04:47:44

问题


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

}

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



回答2:


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




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/2441009/how-to-catch-the-exception-in-initialization-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!