Question: Try,Catch,Finally

  • Thread starter Thread starter VB Programmer
  • Start date Start date
V

VB Programmer

I usually put my declarations for db connections, datasets, datareaders,
etc... above the Try portion. Inside the Try is where I open my connection,
executereader, etc... In the Catch portion I usually "clean it up", with
closing the datareaders, connections, etc... Is this the best way to do it?

The reason I ask is that if something fails (in the Try) and it didn't, get
to open the db connection yet, it will jump to Finally and that will give me
an error because I cannot close a db connection that is not open. Is there
another way around this?
 
The solution is to write a routine that "safely" closes a Connection, and
use that in the Finally block. Here's an example:

Shared Function CloseConn(ByRef objConn As SqlConnection, _
ByRef objCommand As SqlCommand) As Boolean
Try
If Not IsNothing(objConn) Then objConn.Dispose() ' Calls
Close() if objConn is Opened
If Not IsNothing(objCommand) Then objCommand.Dispose()
Return True
Catch E As Exception
HandleError(E) ' Our implementation of this writes a message
to the Event Log
Return False
End Try
End Function

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
http://www.takempis.com
Complex things are made up of
lots of simple things.
 
Back
Top