Re: Database connections and try catch finally?
- From: "Miha Markic [MVP C#]" <miha at rthand com>
- Date: Tue, 11 Oct 2005 14:29:19 +0200
Hi Kenneth,
You should use try/finally scenario (or "using" C# keyword which does the
same).
You never know when you'll get an exception doing database IO.
--
Miha Markic [MVP C#]
RightHand .NET consulting & development www.rthand.com
Blog: http://cs.rthand.com/blogs/blog_with_righthand/
"Kenneth Myhra" <dontspamme@xxxxxxxxxxxxxxxx> wrote in message
news:uBGDIklzFHA.2640@xxxxxxxxxxxxxxxxxxxxxxx
> Hi guys & girls!
>
> We're having a discussion at work whether we should use a try catch
> finally statement when opening a database connection, so that we can close
> the database connection in the finally statement.
> Some of us think that the try catch finally statement uses too much
> resources to justify using it, while other of us think that closing it in
> the finally statement is a good think, and should always be done.
> I also added some code in the end of this mail to describe in code what
> our disagreement is.
>
> So what is the expert advice?
> Should we use try catch finally statements, or should we stop using them
> and instead rely on the .NET framework releasing our connections if an
> error occurs before we have closed the connection?
> Can we rely on the .NET framework to release our connections before we
> have done it explicitly ourselves?
>
> <code description="With try catch finally statement">
>
> SqlConnection conn = null;
> try {
> conn = new SqlConnection(...);
> conn.Open();
> // Additional code where an error could occur, the database connection
> will then be closed in the finally statemen...
> }
> catch { throw; }
> finally {
> if(conn != null) {
> conn.Close()
> conn = null;
> }
> // ...
> }
>
> </code>
>
>
> <code description="Without try catch finally statement">
>
> SqlConnection conn = new SqlConnection(...);
> // Additional code where an error could occur, the database connection
> will not be closed...
> conn.Open();
> conn.Close()
> conn = null;
> // ...
>
> </code>
>
>
> Best regards,
> Kenneth Myhra
> System Developer
>
.
- References:
- Database connections and try catch finally?
- From: Kenneth Myhra
- Database connections and try catch finally?
- Prev by Date: Re: in detail ado find problem
- Next by Date: Re: Database connections and try catch finally?
- Previous by thread: Re: Database connections and try catch finally?
- Next by thread: Re: Database connections and try catch finally?
- Index(es):
Relevant Pages
|