help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Exceptions are not cought


From: Larry Smith
Subject: Re: Exceptions are not cought
Date: Sun, 18 Nov 2007 03:46:37 GMT
User-agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.8) Gecko/20070803 SUSE/1.1.5-0.1 SeaMonkey/1.1.5

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
...




reply via email to

[Prev in Thread] Current Thread [Next in Thread]