gpt4 book ai didi

c++ - 我仍然可以从 catch block 中调用的函数中重新抛出异常吗?

转载 作者:太空狗 更新时间:2023-10-29 23:50:15 25 4
gpt4 key购买 nike

我在遗留代码库中有以下结构:

try{
...
}
catch(Type1&){
...
}
catch(Type2&){
...
}
...

通过复制粘贴开发,相同的 catch block 随处可见。现在,我会写一个这样的函数:

void catchErrors(){
try{
throw;
}
catch(Type1&){
...
}
...
}

然后像这样把它放到代码中:

try{
...
}
catch(...){
catchErrors();
}

这会是一个有效的重构,从而产生相同的功能吗?
(您对重构有什么更好的建议吗?)

最佳答案

是的,这是有效的。

[C++14: 15.1/8]: A throw-expression with no operand rethrows the currently handled exception (15.3). The exception is reactivated with the existing exception object; no new exception object is created. The exception is no longer considered to be caught; therefore, the value of std::uncaught_exception() will again be true.

[ Example: code that must be executed because of an exception yet cannot completely handle the exception can be written like this:

try {
// ...
} catch (...) { // catch all exceptions
// respond (partially) to exception
throw; // pass the exception to some
// other handler
}

—end example ]

[C++14: 15.1/9]: If no exception is presently being handled, executing a throw-expression with no operand calls std::terminate() (15.5.1).

虽然 throw-expression 已经被移动到它自己的函数中,但在它执行期间仍然会处理异常,所以它仍然有效:

#include <iostream>

void bar()
{
try {
throw;
}
catch (int x) {
std::cerr << "Damn " << x << "!\n";
}
}

void foo()
{
try {
throw 42;
}
catch (...) {
bar();
}
}

int main()
{
foo();
}

// Output: Damn 42!

( live demo )

关于c++ - 我仍然可以从 catch block 中调用的函数中重新抛出异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32945739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com