Exceptions & Open Connections

  • Thread starter Thread starter Raterus
  • Start date Start date
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
 
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.
 
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
 
Back
Top