是否可以将异常传递给处理程序,然后重新引发原始异常
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();
}
不同的项目将使用具有不同错误处理技术的此类。
项目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
的子类,Handler2
将抛出异常的副本,并丢失任何派生的类信息,这几乎是肯定的
有没有一种好的方法可以重新抛出原始异常,甚至是同一类型的副本?
您可以使用裸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.");
}
}
};
问题是不能抛出引用。Throw需要对象的真实副本。副本正在对抛出点处的类型引用进行切片。
我不知道这个问题有什么解决办法。
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 这是我尝试让用户将值输入到数组中.然后将其隐藏为大量的星号
- boost::asio如何生成多个协同程序,然后加入它们
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- 为什么异常不退出程序?
- 在std::thread中,joinable()然后join()线程安全吗
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- GDB 捕获抛出,然后忽略异常
- 我想捕获一个异常,并将其绑定到我自己的异常中,然后向上抛出
- 是否可以将异常传递给处理程序,然后重新引发原始异常