mysql_real_connect崩溃、未经处理的异常
背景
近期客户测试软件,功能里有mysql连接问题,在mysql连接失败时,客户机器上出现“已停止工作”界面,而我机器上软件直接退出没有提示自动关闭。
查找分析
因为是一直用的代码,和网上代码对比mysql_real_connect也用法一样,想不到哪里错误,就先加上mysql的option处理代码,类似如下。
unsigned int timeout = 5;
int ret = mysql_options(_connectionHandlerPtr, MYSQL_OPT_CONNECT_TIMEOUT, (const char *)&timeout);
if (ret) {
throw DataBaseError("mysql参数设置失败");
return;
}
if (NULL == mysql_real_connect(_connectionHandlerPtr, server.c_str(), user.c_str(), password.c_str(), database.c_str(), import, NULL, 0))
{
throw DataBaseError("连接数据库失败");
return;
}
char value = 1;
mysql_options(_connectionHandlerPtr, MYSQL_OPT_RECONNECT, &value);
加了还是不行,不过用代码调试运行报“未经处理的异常”,就查try,catch代码,把catch里括号里参数类型里*去掉,“未经处理的异常”不报了,mysql_real_connect也不崩溃了。
未经处理的异常
从msdn里查下try catch的描述。
try {
// code that could throw an exception
}
[ catch (exception-declaration) {
// code that executes when exception-declaration is thrown
// in the try block
}
[catch (exception-declaration) {
// code that handles another exception type
} ] . . . ]
// The following syntax shows a throw expression:
throw [expression]
exception-declaration不是无变化的意思,它是和throw的值类型有关的,如果throw "abc",则catch里可以带*号是char*,如果throw CXXError,就要catch(CXXError e),抛出什么类型就要catch什么类型,如果类型不一致,则会报“未经处理的异常”。
mysql_real_connect崩溃
mysql_real_connect连接失败是会正常上报,代码对应处理时会throw,是throw的问题,mysql_real_connect没有问题。