C ++如何处理泛型catch处理程序中抛出的异常

时间:2015-11-19 13:36:44

标签: c++

有没有办法处理泛型catch块中抛出的异常。

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

由于

2 个答案:

答案 0 :(得分:8)

您可以使用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是共享所有权智能指针。

答案 1 :(得分:0)

问题在于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
}
相关问题