简体   繁体   中英

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;
    }
}

The above code gives the output:

Unknown exception in inner block    
Integer Exception 20

I read in an answer that it is not possible to determine the exception in a catch all block.

When you write throw; , the C++ compiler rethrows the caught exception by reference .

It's almost as if the catch (...) was not there, barring the intercepting std::cout statement.

So it's re-caught at the int e catch site.

C++11 goes some way in allowing you to capture the exception in a catch block, including catch (...) , but there is no portable way of inspecting the exception caught in a catch (...) block. See http://en.cppreference.com/w/cpp/error/current_exception .

Rethrowing exception does not generate new exception object. Instead it continues throwing the same exception object.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM