How to catch an exception in the initialization list?

I have a question on how to catch an 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) {} } 
+7
c ++ initialization-list
source share
4 answers

I think the syntax is similar to this (although it’s better to catch such things with the caller. And what are you going to do once you catch it?)

 Bar::Bar() try : Foo(1) { } catch( const SomeException &e ) { } 
+10
source share

C ++ has a mechanism for this, but it is rarely used. This is the try try function block:

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

See this classic gotw for a discussion of why it should only be used to throw exceptions (for example, the type of the exception FooException becomes BarException).

+6
source share

I believe that this should be caught by the object creation procedure.

+1
source share

Consider replacing a complex instance of boost::optional . Then you can defer its initialization to the constructor body.

0
source share

All Articles