user3068649
user3068649

Reputation: 421

How to throw an exception in the following C++ code

My class SystemManager() has a private object called myObject whose constructor requires an instance of another class.

How can I throw an exception in case new fails?

The.cpp:

SystemManager::SystemManager(): myObject(new TCPServer()) {  
    ...
}

The .h:

class SystemManager{
    ...
    MyObject myObject;
}

Upvotes: 3

Views: 101

Answers (2)

Alex
Alex

Reputation: 3381

In this case new already throws an exception, but imagine others cases, where you don't use new operator, for example:

MyClass::MyClass( int var1, int var2 )
    : m_var1( var1 ),
      m_obj2( var1 ) // If this one throws an exception,
                     // it can't be caught.
{
    try
    {
       // Constructor body.
    }
    catch( ... )
    { }
}

So, to catch an exception from the initializer list you have to use a special kind of try-catch

MyClass::MyClass( int var1, int var2 )
    try : m_var1( var1 ),
          m_obj2( var1 )    // Now I can catch the exception.
{
    // Constructor body.
}
catch( ... )
{ }

Source: https://weseetips.wordpress.com/tag/exception-from-constructor-initializer-list/

Upvotes: 5

Chris Beck
Chris Beck

Reputation: 16224

new already throws an exception if it fails. If the constructor of TCP_server fails, then it also should throw an exception. So you don't have to do anything in the SystemManager ctor.

Upvotes: 2

Related Questions