c++ - 我怎样才能从构造函数中成员的默认初始化中捕获异常?

标签 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/

相关文章:

c++ - 为什么在发送几 block 数据后文件上传停止(使用 multipart/form-data)?

c++ - 如何使用 C++ 和 PDCurses 显示可变字符串?

c++ - 找到第 N 个最小的整数

具有其他类数据类型的 C++ 构造函数

c++ - 如何在不声明类型的情况下将模板发送到另一个模板?

c++ - 使用 usleep 控制循环时间

c++ - 使用 std::async 准备就绪后立即显示结果

c++ - C++中python dict和tr1::unordered_map的区别

c++ - Qlabel settext 正在崩溃

c++ - 如何区分(重载时)operator++ 的前缀和后缀形式? (C++)