导致中止的未捕获异常

Uncaught exception that causes Abort

本文关键字:捕获异常      更新时间:2023-10-16

我使用自己的Exception类,该类继承自std::exception。我很确定这门课还可以,因为它一直到现在都很好。我试图从构造函数抛出一个错误:

DataBase::DataBase()
  : _result(NULL)
{
  mysql_init(&_mysql);
  mysql_options(&_mysql,MYSQL_READ_DEFAULT_GROUP,"option");
  if(!mysql_real_connect(&_mysql,"localhost","root","","keylogger",0,NULL,0))
    throw Exception(__LINE__ - 1, __FILE__, __FUNCTION__, "Can't connect to DB");
}

这是我的尝试/捕获块:

int main(int, char **)
{
  //[...]
  Server server([...]); // DB is a private member in Server
  try
  {
    server.fdMonitor();
  }
  catch (Exception &e)
  {
    std::cout << "Error: in " << e.file() << ", " << "function " << e.function()
          << "(line " << e.line() << ") : " << std::endl
          << "t" << e.what() << std::endl;
  }
  return (1);
}

问题是从我的DB构造函数抛出的Exception没有被捕获。这是中止消息:

 terminate called after throwing an instance of 'Exception'
     what(): Can't connect to DB
 Aborted

有什么想法吗?提前谢谢。

根据您的描述,听起来DataBase构造函数是从Server构造函数调用的。

因此,您需要将该行移动到try块中:

try
{
    Server server([...]); // DB is a private member in Server
    server.fdMonitor();
}
catch (Exception &e)
{
    // ...
}

问题是抛出(server的构造)的位置不在try块内。