[英]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.