导致Abort的未捕获异常

时间:2014-11-06 10:35:17

标签: c++ exception exception-handling

我正在使用继承自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");
}

这是我的try / catch块:

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);
}

问题是没有捕获从我的数据库构造函数抛出的异常。这是中止消息:

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

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

2 个答案:

答案 0 :(得分:3)

从您的描述中,听起来似乎是从DataBase构造函数调用Server构造函数。

因此,您需要将该行移至try块:

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

答案 1 :(得分:1)

问题是抛出的地方(server的构造)不在try区块内。

相关问题