[2005] Try/Catch and Using
Guys,
I'm fairly comfortable with the concept of Try/Catch/Finally but recently I'm trying to use the 'using' statement more often and this has confused me.
I have some code that looks like this....
Code:
Using conSQL As New SqlConnection(ConnectionString)
conSQL.Open()
Using txSQL As SqlTransaction = conSQL.BeginTransaction
Using cmdInsert1 As New SqlCommand("StoredProc1", conSQL, txSQL)
cmdInsert1.CommandType = CommandType.StoredProcedure
'add parameters here...
cmdInsert1.ExecuteNonQuery()
End Using
Using cmdInsert2 As New SqlCommand("StoredProc2", conSQL, txSQL)
cmdInsert2.CommandType = CommandType.StoredProcedure
'add parameters here...
cmdInsert2.ExecuteNonQuery()
End Using
txSQL.Commit()
End Using
End Using
Can anyone tell me how I should be using try/catch blocks in such code to handle exceptions?
Does the try/catch go inside the using statement or do I wrap the entire 'using block' in a try/catch?
Thanks in advance for your time, much appreciated.
Chris.
Re: [2005] Try/Catch and Using
This code:
vb.net Code:
Dim myDisposableObject As New DisposableObject
Try
'Do something here.
Catch
'Handle error here.
Finally
'Clean up here.
myDisposableObject
End Try
is equivalent to this:
vb.net Code:
Using myDisposableObject As New DisposableObject
Try
'Do something here.
Catch
'Handle error here.
End Try
End Using
The Using block simply makes the Finally block redundant, although there are still reasons that you'd use a Finally block apart from disposing.