Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用未捕获_异常处理错误条件_C++_Exception Handling_Uncaught Exception - Fatal编程技术网

C++ 使用未捕获_异常处理错误条件

C++ 使用未捕获_异常处理错误条件,c++,exception-handling,uncaught-exception,C++,Exception Handling,Uncaught Exception,我有以下问题 我有可回收的数据库连接(放回池中) 例如: { session sql(conn_str); // take connection from pool sql.exec("insert into ...") } // at the end of the scope return connection to pool 然而,在某些情况下,回收可能是错误的-例如断开连接,或其他一些重大错误 所以我想自动防止连接被回收。我想 使用std::uncaught\u exception

我有以下问题

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

例如:

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

 sql.exec("insert into ...")
} // at the end of the scope return connection to pool
然而,在某些情况下,回收可能是错误的-例如断开连接,或其他一些重大错误

所以我想自动防止连接被回收。我想 使用
std::uncaught\u exception
实现以下技术 将检测异常并防止回收:

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();
      }
   }
}
现在,我知道这并不建议使用
std::uncaught_exception
在另一种情况下,我也没有发现我的代码有任何错误, 本文提供了讨论的示例

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

注意:

  • 我希望此更改是非侵入性的,以便SQL后端能够抛出而不是检查每一个案例,无论它是否关键
  • 我不希望用户对此采取任何行动,这样对他来说是透明的

  • 我不认为你的方法比更直接的方法有任何优势:

    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的函数文档:

    特别是,当从异常解除期间调用的析构函数调用时,uncaught_exception将返回true


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

    我之所以不使用此方法,是因为它要详细得多。因此,如果你有24个函数做同样的事情,“guard”是解决这类问题的更简单、更清晰的方法。另外,
    std::uncaught_exception()
    是标准函数,可能不像try/catch那样常用。是否有任何特定的场景使用
    std::uncaught_exception()
    这个特殊情况有问题吗?@Artyom,我不知道有什么问题,但正如你所说,这是一个很少使用的函数。我在我的回答中添加了一个支持性陈述。