如何在不同的上下文(例如线程)中保留原始异常类型信息
How to preserve original exception type info accross different contexts (e.g. threads)?
作为我关于从std::rethrow_exception(e);
捕获正确异常问题的后续问题,其中e是std::exception_ptr,我想知道如何将原始异常信息保留在当前异常块之外?
在库中,我在不同的地方保存exception_ptr实例,因此(理论上)应该可以获得原始异常及其包含的所有信息,例如错误报告函数中的信息。异常指针是在catch子句中为一个异常基类创建的,因此std::make_exception_ptr只创建基类型异常的副本,而不是原始异常(这就是我在链接问题中看到的问题)。
存储引用当然是个坏主意(实际的异常对象早就不见了)。存储异常的副本(通过基于类型)会给我带来同样的对象切片问题,就像使用std::exception_ptr时一样。那么,我还有什么其他选择呢?
std::exception_ptr DefaultErrorStrategy::reportError(Parser *recognizer) {
// If we've already reported an error and have not matched a token
// yet successfully, don't report any errors.
if (inErrorRecoveryMode(recognizer)) {
return nullptr; // don't report spurious errors
}
beginErrorCondition(recognizer);
std::exception_ptr result = nullptr;
try {
// We are called from catch() clauses, so we can just rethrow the current exception and catch
// the original exception type, so we don't lose information (caused by object slicing).
throw;
} catch (NoViableAltException &ne) {
result = std::make_exception_ptr(ne);
reportNoViableAlternative(recognizer, ne);
} catch (InputMismatchException &ne) {
result = std::make_exception_ptr(ne);
reportInputMismatch(recognizer, ne);
} catch (FailedPredicateException &ne) {
result = std::make_exception_ptr(ne);
reportFailedPredicate(recognizer, ne);
} catch (RecognitionException &ne) {
result = std::make_exception_ptr(ne);
recognizer->notifyErrorListeners(ne.getOffendingToken(), ne.what(), result);
}
return result;
}
这个函数的调用方式如下:
try {
visitState(p);
}
catch (RecognitionException &e) {
setState(_atn.ruleToStopState[p->ruleIndex]->stateNumber);
getContext()->exception = getErrorHandler()->reportError(this);
recover(e);
}
更新:
我在错误的假设下创建了该代码(current_exception和make_exception_ptr做了相同的操作->创建副本)。事实并非如此,这个答案中的代码确实是错误的,我保留它只是为了参考,如何而不是这样做。
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 为多个会话保留XPtr
- 将浮动的heightmap数组导出为16位原始值
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 有没有办法从非C/C++文件中读取C++原始字符串文字的内容
- 访问"std::vector"的保留但未调整大小的内存作为原始内存是否安全?
- 更改保留指向其字段的原始指针的对象地址
- STL 排序,保留原始顺序
- 如何在保留原始索引的同时对向量的向量进行排序
- 如何修复"文件保留原始位置,复制后不复制扩展名"?
- 如何在被调用后保留数组的原始值
- 如何在使用x进行计算时保留原始x的值
- 矢量元素如何在矢量 std::move 之后保留其原始地址
- 如何在不同的上下文(例如线程)中保留原始异常类型信息
- C++快速排序向量并保留原始索引号
- 在哪里可以找到保留标识符"__CLIBNS"的原始定义?
- 对容器进行排序,然后在保留原始排序的情况下移动元素
- 如果对赋给指针的迭代器进行自增操作,该指针是否保留原始内存位置?
- 保留指定的原始大小
- 在保留原始索引的同时对值进行更快的排序