DeMama
DeMama

Reputation: 1202

MySQL try-catch not working properly

I'm trying to catch error 1045 (access denied) from MySQL, but i'm having some weird issues.. Is there something wrong with my code ?

Instead of handling the exception it throws me one in VS ?

private bool connOpen()
{
    bool kleir = false;
    try
    {
        conn.Open();
        kleir = true; // throws exception here
    }
    catch (MySqlException ex)
    {
        switch (ex.Number)
        {
            case 1045:
                MainWindow.connError = true;
                break;
        }
        kleir = false;
    }
    return kleir;
}

Upvotes: 0

Views: 354

Answers (2)

ChrisLively
ChrisLively

Reputation: 88052

Assuming you are debugging this in VS. VS will stop on the exception even though you have an exception handler because you are in debug mode. If you run this outside of studio, then the exception will be handled by the block. You should also be able to simply hit F5 (Run) in order to continue.

But that, in my opinion, is just a side show. The code you've shown is pretty bad. This snippet implies that you are opening a single connection, using that to make one or more DB calls, then somewhere along the way you have another method to close it.

You should never initialize/manage connections away from where you are actually using them. The connection pool is more than capable of properly handling a large number of connect/disconnects. The reason you should keep that code together is simply that the more things in between open/close on the connection then the more opportunities your code has of not properly disposing of those objects. When they aren't disposed of then the connection pool will crater with very odd and difficult to debug issues and memory usage goes way up.

The connection and command database objects are unmanaged objects. They implement IDisposable because they control unmanaged resources. An example of the right way of doing this is:

using (SqlConnection conn = new SqlConnection(connstring)) {
  using (SqlCommand cmd = new SqlCommand(conn)) {
    // do atomic database stuff
  }
}

The using statements will automatically close and dispose of those objects. The connection pool (that you don't even have to think about) will ensure that if you call the above code 1000 times, that it still runs super fast.

Upvotes: 1

Steve
Steve

Reputation: 216303

I suspect that the exception is thrown when you try to open the connection, but the Dialog in menu DEBUG.Exceptions.Common Language Runtime Exceptions has the checkbox marked under the column Thrown. This should be the reason why your code stops at the line shown and do not enter the catch block

Upvotes: 0

Related Questions