gpt4 book ai didi

c++ - 导致中止的未捕获异常

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

我正在使用我自己的 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 block :

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

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

最佳答案

根据您的描述,DataBase 构造函数似乎是从 Server 构造函数调用的。

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

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

关于c++ - 导致中止的未捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26777250/

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