在阅读 Hurb Sutter 的“More Exceptional C++”时,我偶然发现了以下代码:
// Example 19-5: Alternative right solution
//
T::Close()
{
// ... code that could throw ...
}
T::~T() /* throw() */
{
try
{
Close();
}
catch( ... ) { }
}
我的理解是,这不是一个好主意。因为,如果在堆栈展开期间由于异常调用了 T 析构函数,然后 Close() 抛出异常,那么这将导致调用 Terminate()。
有人可以阐明这一点吗?提前致谢。
最佳答案
My understanding was, this is not a good idea. Because, if T destructor is called during stack unwinding due to an exception, and then Close() throws an exception, then this will cause Terminate() to be called.
try
-catch
block 正是为了防止这种情况。代码:
try
{
Close();
}
catch( ... ) { }
将捕获 Close
抛出的任何异常并忽略它们。因此析构函数不会抛出任何可能导致调用终止函数的异常。
关于c++ - 在析构函数中尝试 Catch block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31483831/