gpt4 book ai didi

C++ try-catch 异常处理约定

转载 作者:太空狗 更新时间:2023-10-29 20:27:07 25 4
gpt4 key购买 nike

这可能是一个微不足道的问题 - 但对我来说并不明显,所以我需要一些确认。假设我在函数中有一个 try-catch block :

int function some_crap() {
some_type b;
int a = 10;
try {
a = boost::numeric_cast<int>(b);
}
catch(boost::bad_numeric_cast& e) {
std::cout << e.what() << std::endl;
return a;
}
catch(...) {
//-Handle other unknown exceptions
return a;
}
return a;
}

IIRC,我需要在每个 catch block 中放置 return a 语句,对吗?同样在每个 catch block 中,a 的值为 10,对吧?

感谢您的时间和兴趣。--T

最佳答案

IIRC, I need to put the return a statements in each of the catch blocks, right?

不,在这种情况下不是。重要的是你不会在没有返回任何东西的情况下离开你的值返回函数的末尾(到 6.6.3/2 这将是未定义的行为)。

因为你有一个返回语句:

return a;

在你的函数结束时,你的 catch block 不需要包含一个。

此外,如果在发生错误时没有任何值可返回,您可以通过执行以下操作重新抛出当前处理的异常:

throw;

或者完全避免捕获并重新抛出该异常,并通过省略相应的 catch block 让它传播,以防您对如何恢复和/或您没有足够的了解不需要记录任何消息。

让异常向上传播调用堆栈可能比只返回一个硬编码值(例如 10)更有意义。

关于第二个问题:

Also in each of the catch blocks, a will have the value 10, right?

是的,这是有保证的。

关于C++ try-catch 异常处理约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17241260/

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