为什么 `catch` 会在这里捕获抛出的东西?
Why does `catch` catch the throw here?
我不太确定这里发生了什么。很明显,为什么内层的 catch 会捕获 throw 2
,但为什么外层的 catch(int x)
会捕获 throw
?我认为 catch(int x)
应该只捕获整数值。第二个 throw
是否可能抛出第一个 cought(即 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 of
the current catch block and passes control to the next matching
exception handler (but not to another catch clause after the same try
block: its compound-statement is considered to have been 'exited'),
reusing the existing exception object: no new objects are made. This
form is only allowed when an exception is presently being handled (it
calls std::terminate if used otherwise). The catch clause associated
with a function-try-block must exit via rethrowing if used on a
constructor.
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)?
正是这样。
我不太确定这里发生了什么。很明显,为什么内层的 catch 会捕获 throw 2
,但为什么外层的 catch(int x)
会捕获 throw
?我认为 catch(int x)
应该只捕获整数值。第二个 throw
是否可能抛出第一个 cought(即 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 of the current catch block and passes control to the next matching exception handler (but not to another catch clause after the same try block: its compound-statement is considered to have been 'exited'), reusing the existing exception object: no new objects are made. This form is only allowed when an exception is presently being handled (it calls std::terminate if used otherwise). The catch clause associated with a function-try-block must exit via rethrowing if used on a constructor.
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)?
正是这样。