Results 1 to 2 of 2

Thread: [2005] Try/Catch and Using

  1. #1

    Thread Starter
    New Member
    Join Date
    Aug 2007
    Posts
    0

    [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.

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: [2005] Try/Catch and Using

    This code:
    vb.net Code:
    1. Dim myDisposableObject As New DisposableObject
    2.  
    3. Try
    4.     'Do something here.
    5. Catch
    6.     'Handle error here.
    7. Finally
    8.     'Clean up here.
    9.     myDisposableObject
    10. End Try
    is equivalent to this:
    vb.net Code:
    1. Using myDisposableObject As New DisposableObject
    2.     Try
    3.         'Do something here.
    4.     Catch
    5.         'Handle error here.
    6.     End Try
    7. 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.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width