try
{
OpenConnection();
RowsAffected = cmd.ExecuteNonQuery();
CloseConnection(true); //should I use this function call here
//as well, when I am using it in finally
//block. For closing database connection.
}
catch (SqlException ex)
{ throw ex; }
finally
{ CloseConnection(true); }
Or Should I write it this way
try
{
OpenConnection();
RowsAffected = cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{ throw ex; }
finally
{ CloseConnection(true); }
No, the finally block gets always executed, regardless of the success or failure of the code in the
tryblock. In your first example the connection would be closed twice on success.You say that you are checking for the connection state so that means you don’t get an exception when closing the connection twice. Still, I think it is more appropriate to try to close it only when necessary.