Source Matters
Source Matters

Reputation: 1221

VB.NET Does SqlConnection get closed automatically in a Try/Catch if exception is thrown?

Didn't find this exact question/answer. In VB.NET, If I open a SqlConnection in a Try/Catch block, and an Exception is thrown (caught properly), is the connection implicitly closed, or do I have to close it? (does it even get opened if the Try failed?)

Would "test" this myself, but I don't really know how to tell if the connection is open or closed when the Exception is thrown.

Thanks!

Upvotes: 4

Views: 3092

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65825

No. That's why you'll want to declare the connection variable before the try/catch and add a finally to it to ensure you have a place where the connection can be closed and disposed:

 Dim con As New SqlClientConnection( . . .)

 Try
      ' DB Operations (create, read, update, delete) here
      con.open()

 Catch SqlClientException (ex)

     ' Deal with exception
 Finally
      ' Code here will always run, whether or not the try code succeeded
      ' or if you wound up in a catch block. You can safely call .close()
      ' or (as shown below) .dispose() because if the connection is already
      ' closed/disposed, the call doesn't do anything.


      ' Dispose is what you want - it will not only close the
      ' connection, but it will release the .NET reference to
      ' the remote resource, freeing up that resource (the database
      ' in this case) to serve other clients.

      con.Dispose()

 End Try

Upvotes: 5

Related Questions