Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > ASP .Net > Question: Try,Catch,Finally

Reply
Thread Tools

Question: Try,Catch,Finally

 
 
VB Programmer
Guest
Posts: n/a
 
      08-07-2003
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?


 
Reply With Quote
 
 
 
 
Kevin Spencer
Guest
Posts: n/a
 
      08-07-2003
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.

"VB Programmer" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed)...
> 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?
>
>



 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off




Advertisments