Try, Catch, Finally – Closing Connections

September 7, 2009

Today I was putting in place exception handling for my latest project, specifically closing database connections when an exception occurs. I though this might be a useful one to share:

DataClassesDataContext DB = null; // The connection object, in this case a LINQ2SQL connection
try
{
 DB = new DataClassesDataContext(ConfigurationManager.ConnectionStrings["fooConnString"].ToString());
 var foo = from x in DB.Y select x;
 // Do something with foo
}
catch (Exception ex)
{
 // Handle exception
}
finally
{
 if (DB != null) DB.Connection.Dispose();
}

Here is the same code, without the connection object initialized to null, and therefore without the null check which results in an error:

Use of unassigned local variable ‘DB’

DataClassesDataContext DB;
try
{
 DB = new DataClassesDataContext(ConfigurationManager.ConnectionStrings["
 DB = new DataClassesDataContext(ConfigurationManager.ConnectionStrings["fooConnString"].ToString());

"].ToString());
var foo = from x in DB.Y select x;
// Do something with foo
}
catch (Exception ex)
{
// Handle exception
}
finally
{
DB.Connection.Dispose();
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: