我有这个抛出异常的构造函数
GenericSocket::GenericSocket(const string& hostname,
const string& servname):
_hostname(hostname),
_servname(servname)
{
initHints();
int rv;
if((rv = getaddrinfo(_hostname.c_str(),
_servname.c_str(),
&_hints,
&_servinfo)) != 0) {
throw GenericSocketException();
}
}
initHints() 执行 _hints 的内存集并设置一些变量。
我用这样的谷歌测试框架测试它:
TEST(CreateObject2, getaddrinfoException)
{
mgs_addrinfo_return = 1;
ASSERT_THROW(new GenericSocket("testhost", "4242"), GenericSocketException);
}
测试失败并出现核心转储:
[ RUN ] CreateObject2.getaddrinfoException
socket creation failed
terminate called after throwing an instance of 'common::GenericSocketException'
what(): Socket creation failed
[1] 43360 abort (core dumped) ./bin/test_common
除了我不知道到底出了什么问题之外,我怀疑一些未初始化的对象被删除了(?),很多事情似乎都在幕后发生,所以我开始怀疑抛出异常是否是一个好习惯一个构造函数。将此功能放在我可以在创建对象后调用的另一个函数中,然后处理异常可能更好吗?
最佳答案
恕我直言,在构造函数中抛出异常是处理这种情况的最佳方式——如果没有套接字,你真的想要一个可用的对象吗?这对我来说没有意义。如果它无法解析该地址,那是有原因的并且值得异常(exception)(只要您正确处理它!)
在您的特定情况下,您应该测试返回值并使异常更有用...(例如,HostNotFound
- 我猜这里就是这种情况)
关于c++ - 在 C++ 类的构造函数中抛出异常是好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4597836/