gpt4 book ai didi

c++ - 为什么 `catch` 在这里 catch ?

转载 作者:行者123 更新时间:2023-12-04 11:58:31 28 4
gpt4 key购买 nike

我不确定这里发生了什么。很明显为什么内扣会捕获throw 2 ,但为什么外面catch(int x)捕获 throw ?我以为catch(int x)应该只捕获整数值。第二个throw有可能吗?抛出什么是第一次咳嗽(这是 2)?

try
{
try
{
throw 2;
}
catch (int n)
{
std::cout << "Inner Catch " << n << std::endl;
throw;
}
}
catch (int x)
{
std::cout << "Outer Catch " << x << std::endl;
}
谢谢!

最佳答案

你不能throw没有。 throw;可以在 catch 块中单独使用来重新抛出当前处理的异常。来自 cppreference :

Rethrows the currently handled exception. Abandons the execution ofthe current catch block and passes control to the next matchingexception handler (but not to another catch clause after the same tryblock: its compound-statement is considered to have been 'exited'),reusing the existing exception object: no new objects are made. Thisform is only allowed when an exception is presently being handled (itcalls std::terminate if used otherwise). The catch clause associatedwith a function-try-block must exit via rethrowing if used on aconstructor.



I thought catch(int x) is supposed to catch integer values only


这就是它的作用。

Is it possible that the second throw throws what was first cought (which is 2)?


正是这样。

关于c++ - 为什么 `catch` 在这里 catch ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68164206/

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