Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Constructors and Exceptions 1

Status
Not open for further replies.

maluk

Programmer
Oct 12, 2002
79
0
0
SG
Hi guys! What is the corrext way to handle exceptions during construction of a member object?

A code snippet is give below:

Code:
class SomeException {};

class A
{
  public:
      A() throw(SomeException)
      {
          if(...)
          {
              throw SomeException();
          }
      }
};

class B
{
  public:
      ...
  private:
      A the_a;
};

int main(int argc, char* argv[])
{
    B the_b; // suppose class A has thrown an exception
             // during class B's construction.
}

As you can see from the code above, class A gets constructed first whenever class B is instantiated. So what is the correct way for class B to handle the exception thrown by class A?

Rome did not create a great empire by having meetings, they did it by
killing all those who opposed them.

- janvier -
 
Wow! I didn't know you could put a try catch block around a constructor's initializer list... But they're right, if a constructor's initializer list throws an exception, all you can really do it re-throw it.

So maluk, to answer your question:
Code:
class B
{
  public:
    B()
    try
    :  the_a()
    {
    } catch (...)
    {
      throw;
    }
      ...
  private:
      A the_a;
};
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top