【发布时间】:2018-08-24 01:10:29
【问题描述】:
struct base
{
base() { throw std::exception(); }
};
struct derived : public base
{
derived() try : base() { }
catch (std::exception& e)
{
std::cout << "exception handled" << std::endl;
}
};
int main()
{
derived a; // My app crashes.
return 0;
}
难道我的应用程序不写“已处理异常”并继续运行吗?
我发现的唯一解决方案是在 try/catch 块中围绕“a”的构造。但是如果我这样做,首先在构造函数中使用 try/catch 有什么意义呢?我猜也许它的用途是清理可能已分配的成员变量?因为没有调用析构函数?
以下工作,但处理异常 2 次。
struct base
{
base() { throw std::exception(); }
};
struct derived : public base
{
derived() try : base() { }
catch(std::exception& e)
{
std::cout << "exception 1" << std::endl;
}
};
int main()
{
// This works fine.
try {
derived a;
}
catch(std::exception& e)
{
std::cout << "exception 2" << std::endl;
}
return 0;
}
我只是想问自己为什么我不应该简单地避开构造函数的 try / catch 语法并写下这个:
struct base
{
base() { throw std::exception(); }
};
struct derived : public base
{
derived() : base() { }
};
int main()
{
// This works fine.
try {
derived a;
}
catch(std::exception& e)
{
std::cout << "exception handled" << std::endl;
}
return 0;
}
【问题讨论】: