繁体   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