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

use*_*708 10 c++ exception-handling exception

我想这样做:

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

在不必为每个子类型编写单独的处理程序的情况下,这是否可行?

Bar*_*rry 5

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

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

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

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