簡體   English   中英

C ++如何處理泛型catch處理程序中拋出的異常

[英]C++ how to get handle to exception thrown in generic catch handler

有沒有辦法處理泛型catch塊中拋出的異常。

try
{
    throw ;
}
catch(...)
{
// how to get handle to exception thrown
}

謝謝

您可以使用std::current_exception

從cppreference重新排列:

#include <string>
#include <exception>
#include <stdexcept>

int main()
{
     eptr;
    try {
        std::string().at(1); // this generates an std::out_of_range
    } catch(...) {
        std::exception_ptr eptr = std::current_exception(); // capture
    }
} 

catch(...)塊內部, exception_ptr eptr捕獲了當前異常。 通過引用的異常對象std::exception_ptr仍然有效,只要仍有至少一個std::exception_ptr被引用它: std::exception_ptr是共享所有權的智能指針。

問題是C ++,允許異常是任何類型,而不僅僅是std::exception的子類。 這就是為什么常見的習慣用法是只使用從std::exception派生的異常類來擁有一個連貫的接口。

您可以隨時使用@PaoloM建議使用std::current_exception() 但它有一些限制使其難以使用 ,因為允許表示任何類型的異常,它只能是std::exception_ptr (參見cpluscplus.com ):

  • 默認構造(獲取空指針值)。
  • 被復制,包括被復制空指針值(或nullptr)。
  • 使用operator ==或operator!=與另一個exception_ptr對象(或nullptr)進行比較,其中兩個空指針始終被視為等效,並且只有兩個非空指針引用相同的異常對象時才被認為是等效的。
  • 在上下文中可轉換為bool,如果具有空指針值則為false,否則為true。
  • 被交換,被毀壞。

如果庫實現支持,則對對象執行任何其他操作(例如解除引用它)會導致未定義的行為。

如果您希望能夠通過異常處理嚴重事務,則應使用專用異常處理程序:

try
{
    throw ;
}
catch (MyException& a) {
// Ok, it is a know type and I know how to deal with it
}
catch (std::exception& e) {
// it is a subclass of std::exception, I can at least use its what() method
catch(...)
{
// I can get a std::exception_ptr from current_exception, but cannot know what to do with it
}

暫無
暫無

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

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