簡體   English   中英

從“全部捕獲”塊中拋出異常如何在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

我讀了一個答案,即不可能在“全部捕獲”塊中確定異常。

當你寫throw; C ++編譯器通過引用重新拋出捕獲的異常。

除非沒有攔截std::cout語句,否則就好像沒有catch (...)

因此它在重新捕獲int e抓現場。

C ++ 11在某種程度上允許您捕獲catch塊中的異常, 包括 catch (...) ,但是沒有可移植的方法來檢查catch (...)塊中catch (...)的異常。 請參閱http://en.cppreference.com/w/cpp/error/current_exception

重新拋出異常不會生成新的異常對象。 而是繼續拋出相同的異常對象。

18.1引發異常[except.throw]

  1. ...如果處理程序通過重新拋出而退出,則控制權將傳遞給同一異常對象的另一個處理程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM