Reputation: 111
I have a mysql program that works most of the time, but I test it with my mysql server shut down and then I start to have problems.
First, I connect to server and try to get database. Since I am running this when my mysql server is shut off, I get exception when I tell it to connect, and then move on. Then later on I want to do some other things with the server and before I do I want to check if the connection is open or if it went away for a reason out of my control.
With the connection failed, and then I call the isClosed() function, my program crashes! I put tests before and after the line of codes and it is clear that once I call isClosed() the program crashes. This does not make sense for isClosed() to crash because how else am I suppose to know if my connection worked?? (well of course if I am in exception block I can know, but just assume I want to be able to ask if it is closed in other places too).
try
{
con = drvr->connect(serverLoginParams.hostname, serverLoginParams.username, serverLoginParams.password);
con->setSchema(db);
}
catch (sql::SQLException &e)
{
std::cout << "# ERR: SQLException in " << __FILE__;
std::cout << "(" << __FUNCTION__ << ") on line "<< __LINE__ << std::endl;
std::cout << "# ERR: " << e.what();
std::cout << " (MySQL error code: " << e.getErrorCode();
std::cout << ", SQLState: " << e.getSQLState() << " )" << std::endl;
}
// ... more code here ... //
if (con->isClosed())
{
// do something
}
Upvotes: 1
Views: 2078
Reputation: 12287
In the code you have listed, it's possible con
is never set to something real.
If drvr->connect(...)
throws an exception, con
will never be set to a valid pointer, so you can't call con->isClosed()
, you're not pointing to a valid connection object.
You need to either move the isClosed()
call into the try
block, or restructure to bail out after detecting that connect()
threw an exception.
It's not the code in the isClosed()
function that is crashing your program, it's the fact you're calling that code on an invalid (potentially nullptr
, you don't show your declaration/initialization) object, which is undefined behavior in C++.
Upvotes: 2