Question: Try,Catch,Finally

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?
 
K

Kevin Spencer

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,968
Messages
2,570,154
Members
46,702
Latest member
LukasConde

Latest Threads

Top