tags:

views:

618

answers:

4

Here's a curious one. I have a class A. It has an item of class B, which I want to initialize in the constructor of A using an initializer list, like so:

class A {
    public:
    A(const B& b): mB(b) { };

    private:
    B mB;
};

Is there a way to catch exceptions that might be thrown by mB's copy-constructor while still using the initializer list method? Or would I have to initialize mB within the constructor's braces in order to have a try/catch?

+1  A: 

I don't see how you'd do that with initializer-list syntax, but I'm also a bit sceptical that you'll be able to do anything useful by catching the exception in your constructor. It depends on the design of the classes, obviously, but in what case are you going to fail to create "mB", and still have a useful "A" object?

You might as well let the exception percolate up, and handle it wherever the constructor for A is being called.

Mark Bessey
+8  A: 

Have a read of http://weseetips.com/2008/06/04/how-to-catch-exceptions-from-constructor-initializer-list/

Edit: After more digging, these are called "Function try blocks".

I confess I didn't know this either until I went looking. You learn something every day! I don't know if this is an indictment of how little I get to use C++ these days, my lack of C++ knowledge, or the often Byzantine features that litter the language. Ah well - I still like it :)

To ensure people don't have to jump to another site, the syntax of a function try block for constructors turns out to be...

C::C()
try : init1(), ..., initn()
{
  // Constructor
}
catch(...)
{
  // Handle exception
}
Adam Wright
Ah... that looks like just the thing!
Head Geek
Ugh. I'm not surprised that there's some way to do that, but it sure is a great example of why I hate C++ initializer syntax...
Mark Bessey
NOTE: you can't handle the exception when using function try blocks on constructors. even if your catch(...) block does not re-throw, the exception still escapes to the caller.
Aaron
Dr Dobbs has detailed explanation of this: http://www.drdobbs.com/cpp/184401297
jwfearn
Herb Sutter's "Guru of the Week" articles also has a nice discussion on function-try-blocks: http://www.gotw.ca/gotw/066.htm
Void
+5  A: 

It's not particularly pretty:

A::A(const B& b) try : mB(b) 
{ 
    // constructor stuff
}
catch (/* exception type */) 
{
    // handle the exception
}
Michael Burr
A: 

It should be pointed out that this is NOT c++. This is part of mickysoft++.

James
Function-try-blocks are standard C++. See the Dr.Dobb's article that posted in jwearn's comment above (http://www.drdobbs.com/cpp/184401297)
Void