A
Andrew
I would like people's opinions on how best to clean up SQL Server
connections and transactions after errors occur while using them. For
example, assume you have the following:
Public Function test()
Dim conn As New SqlClient.SqlConnection("connection string here")
Dim cmd As New SqlClient.SqlCommand("MyStoredProc", conn)
Try
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
Catch ex as Exception
' Possibly do something more than rethrow.
throw ex
Finally
conn.Dispose()
cmd.Dispose()
End Try
End Function
Now let us assume that ExecuteNonQuery() throws a SQL Exception.
1. After the exception, should I still try to call Close() on the connection
in the Catch block?
2. If the answer to #1 is yes, shouldn't one rather move the Close() to the
finally block where it will always be called?
3. Is there a chance that calling Close() will itself throw an exception -
either within the finally or catch blocks?
At the end of the day, what is important is to ensure that this connection
is returned to the connection pool as quickly as possible no matter what the
outcome of the function call.
Thoughts and ideas would be appreciated.
Andrew
connections and transactions after errors occur while using them. For
example, assume you have the following:
Public Function test()
Dim conn As New SqlClient.SqlConnection("connection string here")
Dim cmd As New SqlClient.SqlCommand("MyStoredProc", conn)
Try
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
Catch ex as Exception
' Possibly do something more than rethrow.
throw ex
Finally
conn.Dispose()
cmd.Dispose()
End Try
End Function
Now let us assume that ExecuteNonQuery() throws a SQL Exception.
1. After the exception, should I still try to call Close() on the connection
in the Catch block?
2. If the answer to #1 is yes, shouldn't one rather move the Close() to the
finally block where it will always be called?
3. Is there a chance that calling Close() will itself throw an exception -
either within the finally or catch blocks?
At the end of the day, what is important is to ensure that this connection
is returned to the connection pool as quickly as possible no matter what the
outcome of the function call.
Thoughts and ideas would be appreciated.
Andrew