The prevailing wisdom for coding try/catch statements around db connections seems to be as follows:
conn = new MySqlConnection();
cmdGetDate = new MySqlCommand();
tryMy question is, what if an exception occurs on closing the connection (which is inside the finally part of the try/catch)?
{
conn.ConnectionString = connStringSQL;
conn.Open();
...do some stuff
}
catch (Exception dbErr)
{
throw new Exception(dbErr.Message);
}
finally
{
conn.Close();
cmdGetDate.Dispose();
conn.Dispose();
}
DavePosted Jan 25, 2008, 6:47 PM
Also, the 'behind-the-scenes' try/catch stuff in a using block does not actually let you catch any exceptions that are thrown. You need to nest it in an external try/catch:
The cost of this being the overhead of 2 try/catch statements. (Pretend in my example above that I did not throw a new exception, but handled the one that was thrown).
Let me know if I have this wrong.
Scott LyslePosted Jan 25, 2008, 3:48 AM
You can use "Using" in the declaration of the connection; when this goes of scope or fails it will dispose of the connection.
using (SqlConnection conn = new SqlConnection(ConnString)) { conn.Open(); .... }