为什么`catch`会在这里接住投掷?

我不确定这里发生了什么。很明显为什么内部捕获会捕获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:

重新抛出当前处理的异常。放弃当前 catch 块的执行并将控制权传递给下一个匹配的异常处理程序(但不会传递给同一个 try 块之后的另一个 catch 子句:它的复合语句被认为已“退出”),重用现有的异常对象:没有创建新对象。仅当当前正在处理异常时才允许使用此形式(如果以其他方式使用,则调用 std::terminate)。如果在构造函数上使用,与函数 try-block 关联的 catch 子句必须通过重新抛出退出。


我认为 catch(int x) 应该只捕获整数值

这就是它的作用。

第二次投掷是否有可能抛出第一次咳出的东西(即 2)?

正是这样。

  • @user3265447 there is nothing special about `std::exception` other than it is commonly used when throwing exceptions. You can `throw` and `catch` without a single `std::exception` being involved. And yes, `throw;` outside of a catch block will call `std::terminate`

以上是为什么`catch`会在这里接住投掷?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>