<分区>
在我的构造函数中,我必须初始化 _socket。 但是初始化套接字会抛出异常。 如何捕获并处理异常?
谢谢! 这是我的代码:
tftp_server::tftp_server(unsigned short port_number)
: _socket(_io_service, udp::endpoint(udp::v4(), port_number))
{
//...
}
标签 c++
<分区>
在我的构造函数中,我必须初始化 _socket。 但是初始化套接字会抛出异常。 如何捕获并处理异常?
谢谢! 这是我的代码:
tftp_server::tftp_server(unsigned short port_number)
: _socket(_io_service, udp::endpoint(udp::v4(), port_number))
{
//...
}
最佳答案
您可以使用函数 try block 。
tftp_server::tftp_server(unsigned short port_number)
try
: _socket(_io_service, udp::endpoint(udp::v4(), port_number))
{
//...
}
catch(...)
{
}
但是,引用 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.
换句话说(也是萨特)
the only (repeat only) possible use for a constructor function-try-block is to translate an exception thrown from a base or member subobject
总而言之:您可以这样做,但通常没有意义。
关于c++ - 我怎样才能从构造函数中成员的默认初始化中捕获异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23386107/