Search for who selected an exception from the list of initializers

Suppose I have a class that contains some members of some type. I know that the syntax for blocks try-catchwith initialization lists is as follows

template<int N>
struct Member
{
    Member()
    {
        std::cout << "Default constructor of Member " << N << std::endl;
    }
};

class A 
{
    Member<1> m1;
    Member<2> m2;
    // n members 
public:
A() try
    : m1()
    , m2()
    {
        // constructor implementation
    }
    catch (std::exception const & e)
    {
               // ... cleanup 
        throw; // and rethrow
    }
};

Since the list of initializers is involved, I cannot use multiple catch try blocks. How can I determine which member initiative selected an exception?

+3
source share
2 answers

You can follow the initialization process.

class A 
{
    Member<1> m1;
    bool m1threw = true;
    Member<2> m2;
    bool m2threw = true;
    // n members 
public:
A() try
    : m1()
    , m1threw(false)
    , m2()
    , m2threw(false)
    {
        // constructor implementation
    }
    catch (std::exception const & e)
    {
               // ... cleanup 
        if (m1threw) {
            // 
        }
        else if (m2threw) {

        }
        throw; // and rethrow
    }
};

++ 11. , , - . ,

,

template<int N>
struct Member
{
    Member(int some_arg) 
    {
        std::cout << "Non default constructor of Meber " << N << std::endl;
    }
};

class A 
{
    Member<1> m1;
    Member<2> m2;
   enum TrackerType { NONE, ONE, TWO };
public:
   A(TrackerType tracker = NONE)
   try    // A constructor try block.
     : m1((tracker = ONE, 1)) // Can throw std::exception
     , m2((tracker = TWO, 1)) // Can throw std::exception
     {
         //TODO:
     }
   catch (std::exception const & e)
     {
        if (tracker == ONE) {
           std::cout << "m1 threw: " << e.what() << std::endl;
        }
        else if (tracker == TWO) {
           std::cout << "m2 threw: " << e.what() << std::endl;
        }
        throw;
     }
};

, ++ 11

+3
template<int N>
struct Member
{
    Member()
    {
        std::cout << "Default constructor of Member " << N << std::endl;
        // ...
        if (bad_thing)
        {
            throw N;
        }
    }
};

class A 
{
    Member<1> m1;
    Member<2> m2;
    // n members 
public:
A() try
    : m1()
    , m2()
    {
        // ...
    }
    catch (int N)
    {
        std::cout << "construction of member " << N << " failed" << std::endl;
        // ...
    }
};
+1

All Articles