Stop C ++ class instance

Is there a way to stop a C ++ class if there is an error in the instance? For example, return NULL, maybe? Basically, I have a wrapper class for MySQL, and the constructor makes the connection, but if the connection fails, I want the object to be, um, useless?

PDB::PDB(string _DB_IP, string _DB_USER, string _DB_PASS, string _DB_DB) : _DB_IP( _DB_IP ), _DB_USER( _DB_USER ), _DB_PASS( _DB_PASS ), _DB_DB( _DB_DB ) { mysql_init(&this->mysql); this->connection = mysql_real_connect(&this->mysql, this->_DB_IP.c_str(), this->_DB_USER.c_str(), this->_DB_PASS.c_str(), this->_DB_DB.c_str(), 0, 0, 0); if( this->connection == NULL ) // WHAT SHOULD I DO HERE, OTHER THAN THROW AN ERROR? { cout << mysql_error(&this->mysql) << endl; } this->result = NULL; } 

What should I do in the NULL test, stop creating, etc.

+3
source share
2 answers

An exception throw is the only way to indicate an error at build time.

http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.8

+10
source

If the connection usually breaks, set the flag in the object and provide the class function is_connected () for the class and use it in the application code. If it usually cannot fail, throw an exception. The first is a template that uses the standard C ++ library to open file streams.

+5
source

Source: https://habr.com/ru/post/1334262/


All Articles