我正在使用继承自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
有什么想法吗? 提前谢谢。
答案 0 :(得分:3)
从您的描述中,听起来似乎是从DataBase
构造函数调用Server
构造函数。
因此,您需要将该行移至try
块:
try
{
Server server([...]); // DB is a private member in Server
server.fdMonitor();
}
catch (Exception &e)
{
// ...
}
答案 1 :(得分:1)
问题是抛出的地方(server
的构造)不在try
区块内。