mis*_*sev 6 c++ exception-handling c++11
目标是完全处理循环并抛出之后可能发生的任何异常:
for (...) {
try {
// code that could throw
} catch (const ExceptionObj &ex) {
// save ex and rethrow after the loop
}
}
Run Code Online (Sandbox Code Playgroud)
这样做的最佳做法是什么?在我的特定情况下,保存任何异常都是可以的.
我有几个想法:
复制ex到一个ExceptionObj值.问题:当ex有子类或需要处理更多异常时,根本不能很好地扩展.
有一个clone方法,ExceptionObj在堆上返回一个副本.问题:不适用于第三方例外.
以这种类型擦除的方式处理抛出的异常对象是std::exception_ptr存在的:
std::exception_ptr ex;
for (...) {
try {
// code that could throw
} catch (...) {
ex = std::current_exception();
}
}
if(ex) // Only evaluates to true if a thrown exception was assigned to it.
std::rethrow_exception(ex);
Run Code Online (Sandbox Code Playgroud)
与异常对象的动态类型相关的所有生命周期问题都由标准库处理.您可以将其ex视为异常对象的引用计数句柄,允许您将其提升到try-catch块之外.
这遵循您在帖子中列出的方法,然后在评论中确认,抛出的最后一个异常是重新抛出的异常.