views:

100

answers:

5

Does the following code leave the connection open if there is an exception?

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();
}
+3  A: 
try
catch
finally

is the proper way to handle this, because connection should always be closed at the end. but you should check not only that conn != null, but also if conn state is not Closed.

Robert Koritnik
+6  A: 

Use Using

using(SqlConnection conn = new SqlConnection())
{
//put all your code here.
}
John Hpa
A: 

Why not use a using around the connection as well as the command?

ho1
+10  A: 

The way you are taking care of SqlCeCommand in your code with the help of using block, you could do the same for the SqlCeConnection.

SqlCeConnection conn;
using (conn = new SqlCeConnection(ConnectionString))
{
   conn.Open();
   using (SqlCeCommand cmd = 
       new SqlCeCommand("SELECT stuff FROM SomeTable", conn))
   {
   // do some stuff
   }
}

Note: You can use a using block for classes that implement IDisposable.

EDIT: This is same as

try
{
    conn = new SqlCeConnection(ConnectionString);
    conn.Open();

    SqlCeCommand cmd = conn.CreateCommand();
    cmd.CommandText = "...";

    cmd.ExecuteNonQuery();

finally
{
    conn.Close();
}

ref: http://msdn.microsoft.com/en-us/library/system.data.sqlserverce.sqlceconnection%28VS.80%29.aspx

shahkalpesh
A: 

You should use using statement, which handles the connection closing without hassles http://davidhayden.com/blog/dave/archive/2005/01/13/773.aspx

mamoo