Exceptions & Open Connections

R

Raterus

Hi, quick question..

If I have a try/catch block like this, which I use all the time

Try
conn.Open()
somevar = CStr(cmd.ExecuteScalar())
Catch ex As Exception
Throw
Finally
conn.Close()
End Try

I throw the exception again because this is within my own object, and I am handling the exception on the presentation level (where it will be shown to the user). My question is, will the Finally block still be called?, or should I put a conn.Close before I throw the exception again to ensure that it will be closed. This is an asp.net application if it matters.

Thanks,
--Michael
 
D

David Browne

Yes. The Finally block always runs.

In fact you can just leave out the Catch block if you don't need to do
anything with the exception.

Try
conn.Open()
somevar = CStr(cmd.ExecuteScalar())
Finally
conn.Close()
End Try

David

Hi, quick question..

If I have a try/catch block like this, which I use all the time

Try
conn.Open()
somevar = CStr(cmd.ExecuteScalar())
Catch ex As Exception
Throw
Finally
conn.Close()
End Try

I throw the exception again because this is within my own object, and I am
handling the exception on the presentation level (where it will be shown to
the user). My question is, will the Finally block still be called?, or
should I put a conn.Close before I throw the exception again to ensure that
it will be closed.
 
V

Val Mazur

Hi,

Finally block is called regardless of what happened before. It does nor
matter if your application throws your own exception, Finally block will be
executed.

--
Val Mazur
Microsoft MVP


Hi, quick question..

If I have a try/catch block like this, which I use all the time

Try
conn.Open()
somevar = CStr(cmd.ExecuteScalar())
Catch ex As Exception
Throw
Finally
conn.Close()
End Try

I throw the exception again because this is within my own object, and I am
handling the exception on the presentation level (where it will be shown to
the user). My question is, will the Finally block still be called?, or
should I put a conn.Close before I throw the exception again to ensure that
it will be closed. This is an asp.net application if it matters.

Thanks,
--Michael
 

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

Top