shi*_*ing 8 c++ program-entry-point exception-handling
是否可以在这些场景中处理异常:
Kor*_*icz 22
如何在构造函数中嵌入try-catch的有趣鲜为人知的特性:
object::object( int param )
try
: optional( initialization )
{
// ...
}
catch(...)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
是的,这是有效的C++.这里增加的好处是try会捕获类的数据成员的构造函数抛出的异常,即使它们没有在ctor初始化程序中提到或者没有ctor初始化程序:
struct Throws {
int answer;
Throws() : answer(((throw std::runtime_error("whoosh!")), 42)) {}
};
struct Contains {
Throws baseball;
Contains() try {} catch (std::exception& e) { std::cerr << e.what() << '\n'; }
};
Run Code Online (Sandbox Code Playgroud)