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

Catch and modify std::exception and subclasses, rethrow same type

我想这样做:

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 块中编写模板代码。你能做的最好的就是添加一些运行时类型信息作为字符串:

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