gpt4 book ai didi

c++ - 捕获并修改 std::exception 和子类,重新抛出相同类型

转载 作者:可可西里 更新时间:2023-11-01 16:19:04 26 4
gpt4 key购买 nike

我想这样做:

try
{
// ...
}
catch(const std::exception& ex)
{
// should preserve ex' runtime type
throw type_in_question(std::string("Custom message:") + ex.what());
}

是否有可能无需为每个子类型编写单独的处理程序?

最佳答案

您正在寻找的可能是这样的:

try {
// ...
}
template <typename Exc>
catch (Exc const& ex) {
throw Exc(std::string("Custom message:") + ex.what());
}

至少这就是我们通常在 C++ 中做这样的事情的方式。不幸的是,您不能像那样在 catch block 中编写模板代码。您能做的最好的事情就是将一些运行时类型信息添加为字符串:

try {
// ...
}
catch (std::exception const& ex) {
throw std::runtime_error(std::string("Custom message from ") +
typeid(ex).name() + ": " + ex.what());
}

关于c++ - 捕获并修改 std::exception 和子类,重新抛出相同类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29562056/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com