views:

109

answers:

4
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); }
+8  A: 

No, the finally block gets always executed, regardless of the success or failure of the code in the try block. 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.

Sandor Drieënhuizen
@Sandor: No means,Should not write in try block ? I am checking for conenction state before closing.
Shantanu Gupta
@Shantanu Gupta: that's correct.
Sandor Drieënhuizen
Just a bit of trivia I came across recently - finally blocks do not *always* get called. See Environment.FailFast (http://msdn.microsoft.com/en-us/library/ms131100.aspx)
C.McAtackney
@C.McAtackney: Nice touch. Speaking of exceptional circumstances: in versions of .NET prior to 2.0, a ThreadAbortException could abort the execution of a finally block.
Sandor Drieënhuizen
A: 

Your finally block is always getting executed. Using Close functions like Dispose(), CLose() should be using in finally block

Serkan Hekimoglu
A: 

You should write in the second Way

                try 
                { 
                    OpenConnection(); 
                    RowsAffected = cmd.ExecuteNonQuery();  
                } 
                catch (SqlException ex) 
                { throw ex; } 
                finally 
                { CloseConnection(true); }
ma7moud
+1  A: 

In this particular example, you can in fact do this:

using (var conn = new SqlConnection(...)) {
    // Do work
}

What the compiler does with that statement is essentially:

SqlConnection conn;
try {
  conn = new SqlConnection(...)
} finally {
  conn.Dispose();
}

Or thereabouts... the finally block is always exected, ensuring that a using block always calls Dispose.

The downside of this approach is that you can't catch the SqlException that could be thrown, so you end up doing something like this:

try {
  using (var conn = new SqlConnection(...)) {
    // Do work.
  }
} catch (SqlException ex) {

}

But the compiled code ends up representing:

try {
  SqlConnection conn;
  try {
    conn = new SqlConnection(...);
  } finally {
    conn.Dispose();
  }
} catch (SqlException ex) {

}

To be honest though it probably won't make any difference performance wise, as anytime you throw an exception, its going to be a performance hit. It does ensure that Dispose is always called.

Matthew Abbott