gpt4 book ai didi

c++ - 使用 uncaught_exception 处理错误情况

转载 作者:行者123 更新时间:2023-11-30 04:30:57 25 4
gpt4 key购买 nike

我有以下问题。

我有回收的数据库连接(放回池中)。

例如:

{
session sql(conn_str); // take connection from pool

sql.exec("insert into ...")
} // at the end of the scope return connection to pool

但是在某些情况下,回收可能是错误的 - 例如断开连接或其他一些重大错误。

所以我想自动防止连接被回收。我想要使用 std::uncaught_exception 实现以下技术 - 所以 exec() 函数会检测异常​​并阻止回收:

session::exec(...)
{
guard g(this)

real_exec(...);
}

哪里看守:

class guard {
public:
guard(session *self) : self_(self) {}
~guard() {
if(std::uncaught_exception()) {
self->mark_as_connection_that_should_not_go_to_pool();
}
}
}

现在,我知道 http://www.gotw.ca/gotw/047.htm不建议使用std::uncaught_exception 在另一种情况下,我也没有发现我的代码有任何问题,提供了讨论的示例。

此代码是否存在任何可能的问题。

注意:

  1. 我希望此更改是非侵入式的,以便 SQL 后端能够抛出错误,而不是检查每个案例是否关键。
  2. 我不希望用户对此采取任何行动,因此这对他来说是透明的。

最佳答案

与更直接的方法相比,我认为您的方法没有任何优势:

session::exec()
{
try
{
real_exec();
}
catch(...)
{
mark_as_connection_that_should_not_go_to_pool();
throw;
}
}

如果此解决方案的冗长困扰您,我会注意到他们尚未从 C++ 中删除宏。我不喜欢这个版本,因为它掩盖了底层代码并且有点难看。

#define GUARD try {
#define ENDGUARD } catch(...) { mark_as_connection_that_should_not_go_to_pool(); throw; }

session::exec()
{
GUARD
real_exec();
ENDGUARD
}

另一种可能性是在取得成功之前假设失败。

session::exec()
{
mark_as_connection_that_should_not_go_to_pool();
real_exec();
mark_as_connection_that_may_go_to_pool();
}

最后,为了回答 uncaught_exception 是否会像您概述的那样工作的问题,我将引用 Microsoft 的函数文档:

In particular, uncaught_exception will return true when called from a destructor that is being invoked during an exception unwind.

它似乎完全符合您的预期。

关于c++ - 使用 uncaught_exception 处理错误情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8418367/

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