c++ - 带有 try-catch-rethrow 的代码是否等同于不带 try-catch 的代码?

标签 c++ exception try-catch language-lawyer throw

以下两种代码在什么情况下不等价?

{
  // some code, may throw and/or have side effects
}

try {
  // same code as above
} catch(...) {
  throw;
}

edit 澄清一下,我对 (i) 与上述模式的偏差(例如 catch block 中的更多代码)不感兴趣,也不 (ii) 打算邀请有关适当的光顾评论try-catch block 的用法。

我正在寻找有关 C++ 标准的合格答案。这个问题是由 Cheers and hth. - Alf 的评论提示的。至this answer of mine ,声明没有进一步解释上述代码不等价


edit 他们确实是不同的。堆栈展开将在后者中完成,但不一定在前者中完成,这取决于在运行时是否找到异常处理程序(一些 catch block 在堆栈更高的位置)。

最佳答案

后者要求堆栈展开,而在前者中,如果堆栈展开则由实现定义。

相关标准引用(均来自N3337):

[except.ctor]/1: As control passes from a throw-expression to a handler, destructors are invoked for all automatic objects constructed since the try block was entered. The automatic objects are destroyed in the reverse order of the completion of their construction.

[except.ctor]/3: The process of calling destructors for automatic objects constructed on the path from a try block to a throw-expression is called “stack unwinding.” [...]

[except.terminate]/2: [When the exception handling mechanism cannot find a handler for a throw exception], std::terminate() is called (18.8.3). In the situation where no matching handler is found, it is implementation-defined whether or not the stack is unwound before std::terminate() is called. [...]

因此,如果您想保证自动对象的析构函数在未处理的异常情况下运行(例如,某些持久性存储必须在销毁时发生突变),那么 try {/*code*/} catch (...) {throw;} 会这样做,但 {/*code*/} 不会。

关于c++ - 带有 try-catch-rethrow 的代码是否等同于不带 try-catch 的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33689053/

相关文章:

c++ - 找到稀疏矩阵( Eigen )最大值的有效方法

c++ - 使用多态性时 Unresolved external 问题

c++ - 错误 : invalid use of non-static data member in CPP

c++ - 处理不应崩溃的关键应用程序中的异常

c# - 在 C# 中抛出或不抛出异常

java - 程序在 Thread.sleep() 期间和计时器卡住

assembly - 调用 printf 可以防止段错误

c++ - 遗留 C++ Win32 DLL 中的空终止字符串 - 有更好的方法吗?

java - 如何在 try-with-resource 语句中捕获 close 方法抛出的异常

c++ - 如果数组中传递的项已存在,则抛出数据异常