是否可以将异常传递给处理程序然后重新抛出原始异常?

Is it possible to pass an exception to a handler and then rethrow the original exception?

我正在尝试编写在发生错误时传递给处理程序的代码。

class Handler {
   public: virtual void handle(std::exception const& e) = 0;
};

class DoIt {
  Handler* handler;
  public:
  void doStuff() {
    try {
      methodThatMightThrow();
    } catch (std::exception const& e) {
      handler->handle(e);
    }
  }
  void setHandler(Handler* h) { handler = h; }
  void methodThatMightThrow();

}

不同的项目将使用此 class 和不同的错误处理技术。

项目 1 记录错误

class Handler1: public Handler {
  void handle(std::exception const& e) override {
    logError(e.what());
  }
};

项目 2 传播异常

class Handler2: public Handler {
  void handle(std::exception const& e) override {
    throw e;
  }
};

这两个都应该有效。但是,如果异常是 std::exception 的子 class,Handler2 将抛出异常的副本并丢失任何派生的 class 信息,这几乎可以肯定是。

有没有什么好的方法可以重新抛出原来的异常,甚至是同类型的副本?

问题是你不能抛出引用。 Throw 需要对象的真实副本。副本正在对抛出点的类型的引用进行切片。

我不知道这个问题的解决方法。

您可以使用裸throw重新抛出当前异常。

重写你的 Handler2 以使用它会得到以下代码:

class Handler2 : public Handler
{
public: void handle(const std::exception& ex) const override
    {
        throw;
    }
};

您不必将异常作为参数发送,并且可以编写更高级的处理程序,这些处理程序可以根据异常的类型做不同的事情,例如这个简单的处理程序。

class WrapperHandler : public Handler
{
public:
    void handle() const
    {
        try
        {
            throw;
        }
        catch (const notveryserious_exception& ax)
        {
            std::cout << "Not very serious, I'm going to let this slide." << std::endl;
            std::cout << ax.what() << std::endl;
        }
        catch (const myown_exception& ax)
        {
            // Probably serious, will let this propagate up the stack.
            throw;
        }
        catch (...)
        {
            // Bad, bad, bad.. Unhandled exception that we haven't thrown ourselves.
            throw myown_exception("Unhandled exception.");
        }
    }
};