1

In my constructor, I have to initialize the _socket. But initializing the socket can throw an exception. How can I catch and process the exception ?

Thanks ! Here my code:

tftp_server::tftp_server(unsigned short port_number)
: _socket(_io_service, udp::endpoint(udp::v4(), port_number))
{    
    //...
}
nvoigt
  • 75,013
  • 26
  • 93
  • 142
Cirrus Minor
  • 394
  • 4
  • 14

2 Answers2

3

You can use a function try block.

tftp_server::tftp_server(unsigned short port_number)
try 
    : _socket(_io_service, udp::endpoint(udp::v4(), port_number))
{    
    //...
}
catch(...)
{

}

But, to quote The Herb Sutter (GotW 66):

if the catch block does not throw (either rethrow the original exception, or throw something new), and control reaches the end of the catch block of a constructor or destructor, then the original exception is automatically rethrown.

In other words (also Sutter)

the only (repeat only) possible use for a constructor function-try-block is to translate an exception thrown from a base or member subobject

In summary: you can do that, but there's usually no point.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82
1

See code below:

tftp_server::tftp_server(unsigned short port_number)
try : _socket(_io_service, udp::endpoint(udp::v4(), port_number))
{    
    // Do your stuff
}
catch(...)
{
  // Handle exception
}
101010
  • 41,839
  • 11
  • 94
  • 168
  • There is no way to "handle" a constructor exception. All you can do here is log failure. – DevSolar Apr 30 '14 at 11:01
  • The exception will still leave the constructor - there's no way to prevent that. This construct is only useful for logging, or if you have a badly-designed member that needs some kind of manual clean-up if initialisation fails, which isn't the case here. – Mike Seymour Apr 30 '14 at 11:11
  • Yes DevSolar, it's what I want to do (log error). Thanks ! – Cirrus Minor Apr 30 '14 at 12:09