K
Kenneth Myhra
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
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