当前位置: 动力学知识库 > 问答 > 编程问答 >

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;

}

网友答案:

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/

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: