VB.NET 如果抛出异常,SqlConnection 是否会在 Try/Catch 中自动关闭?
VB.NET Does SqlConnection get closed automatically in a Try/Catch if exception is thrown?
没有找到确切的 question/answer。在 VB.NET 中,如果我在 Try/Catch 块中打开一个 SqlConnection,并抛出一个异常(正确捕获),连接是隐式关闭,还是我必须关闭它? (如果尝试失败,它甚至会打开吗?)
我自己会 "test" 这个,但我真的不知道在抛出异常时如何判断连接是打开还是关闭。
谢谢!
不。 这就是为什么您要在 try/catch 之前声明连接变量并向其添加 finally 以确保您有连接的地方可以关闭和处置:
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
没有找到确切的 question/answer。在 VB.NET 中,如果我在 Try/Catch 块中打开一个 SqlConnection,并抛出一个异常(正确捕获),连接是隐式关闭,还是我必须关闭它? (如果尝试失败,它甚至会打开吗?)
我自己会 "test" 这个,但我真的不知道在抛出异常时如何判断连接是打开还是关闭。
谢谢!
不。 这就是为什么您要在 try/catch 之前声明连接变量并向其添加 finally 以确保您有连接的地方可以关闭和处置:
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