从 "catch all" 块中重新抛出异常如何在 C++ 中生成相同的异常?

How does rethrowing an exception from a "catch all" block generate the same exception in C++?

#include<iostream>
#include<exception>
using namespace std;

int main()
{
    try{
        try{
            throw 20;
        }catch(...)
        {
            cout<<"Unknown exception in inner block"<<endl;
            throw;
        }
    }catch(int e)
    {
        cout<<"Integer Exception "<<e<<endl;
    }catch(...)
    {
        cout<<"Unknown exception in outer block"<<endl;
    }
}

以上代码给出了输出:

Unknown exception in inner block    
Integer Exception 20

我在回答中读到无法确定 catch all 块中的异常。

当您编写 throw; 时,C++ 编译器通过引用重新抛出捕获的异常

几乎就好像 catch (...) 不存在一样,除非拦截 std::cout 语句。

所以它在 int e 捕获点被重新捕获。

C++11 在某种程度上允许您在 catch 块中捕获异常,包括 catch (...),但是没有可移植的方法来检查在 catch (...) 块中捕获异常。参见 http://en.cppreference.com/w/cpp/error/current_exception

重新抛出异常不会产生新的异常对象。相反,它会继续抛出相同的异常对象。

18.1 Throwing an exception [except.throw]

  1. ... If a handler exits by rethrowing, control is passed to another handler for the same exception object.