[英]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 ):
如果庫實現支持,則對對象執行任何其他操作(例如解除引用它)會導致未定義的行為。
如果您希望能夠通過異常處理嚴重事務,則應使用專用異常處理程序:
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.