Correct way to close database connection in event of exception.
- by lowlyintern
/I have some code of of the following form.
Does this mean the connection is left open if there is an exception?
Note, I am using a Microsoft SQL compact edition database./
try
{
SqlCeConnection conn = new SqlCeConnection(ConnectionString);
conn.Open();
using (SqlCeCommand cmd = new SqlCeCommand("SELECT stuff FROM SomeTable", conn))
{
// do some stuff
}
conn.Close();
}
catch (Exception ex)
{
ExceptionManager.HandleException(ex);
}
/*Surely a better way would be to declare a connection object before the try, establish
a connection inside the try block and close it in a finally block?
*/
SqlCeConnection conn = null;
try
{
conn = new SqlCeConnection(ConnectionString);
conn.Open();
using (SqlCeCommand cmd = new SqlCeCommand("SELECT stuff FROM SomeTable", conn))
{
// do some stuff
}
}
catch (Exception ex)
{
ExceptionManager.HandleException(ex);
}
finally
{
if( conn != null ) conn.Close();
}