Stefan Kristensen wrote: > Hello again :-) > > In my everlasting search for knowledge, I have come to the issue of > databases. I am using MySQL on a FreeBSD box. > > After some issues with include paths and libraries, I managed to get in > contact with the database and retrieve some records so the program and > database works. Time to combine with some of the other stuff I have > learned: > > When connecting to the database, I used the following: > if(!mysql_real_connect(connect,SERVER,USER,PASSWORD,DATABASE,0,NULL,0)){ > cout << "Oops: " << mysql_error(connect) << endl; > return 1; > } > > This works as it should and tells me if the connection fails (e.g. wrong > password). > > But if I do this instead: > try{ > mysql_real_connect(connect,SERVER,USER,PASSWORD,DATABASE,0,NULL,0); > }catch(...){ > cout << "Oops: " << mysql_error(connect) << endl; > return 1; > } > > I get the following error: Segmentation fault (core dumped) (i.e. not > the mysql error as expected). > > What am I doing wrong? > > Best regards > Stefan > > > Oh, and I still wonder why #include <mysql/mysql.h> doesn't work, but I > have to use the -Ipath-to-mysql.h option?
Well.. try/catch blocks catch C++ objects (exceptions, strings int's, etc) thrown within the 'try' clause. I imagine that mysql_real_connect() is either a C function or is a C++ function that does NOT throw anything - hence there is nothing to 'catch' and your code continues at the line FOLLOWING the 'catch' block. try/catch has nothing to do with the return value of mysql_real_connect(). usually, try/catch blocks are not used for simple constructs as in your example - unless the C++ functions called inside the 'try' block actually 'throw' something themselves. Any good C++ book should have examples of using try/catch. try { if ( !mysql_real_connect( connect, SERVER, USER, PASSWORD, DATABASE, 0, NULL, 0 ) ) { throw 1; } // code here executes if mysql_real_connect() did not fail ... } catch (...) { // code here executes if anything is thrown by any // code or function within the 'try' block cout << "Oops: " << mysql_error(connect) << endl; return 1; } // code here executes if mysql_real_connect() did not fail ... _______________________________________________ help-gplusplus mailing list help-gplusplus@gnu.org http://lists.gnu.org/mailman/listinfo/help-gplusplus