Handle and diagnose database connection exceptions

When working with databases, you should be a bit pessimistic. Databases are sometimes down, under maintenance, etc. so they aren’t tend to be available in all cases. Because of this, there’s much need for error-handling logic in your data access code.

This task doesn’t require anything else than you probably know already: use try/catch/finally blocks. You should put anything that might cause an exception into a try block. Then write your error-handling code in catch blocks, and use multiple ones, if you see fit. The last thing to do is to implement a finally block, where you should close your connection and perform cleanup. Because you probably want to use your object which caused an error in a finally block, don’t declare it within a try block, because it won’t be accessible (its scope will be the try block). After all these advices, let’s see a code example:

SqlConnection theConnection = new SqlConnection();
theConnection.ConnectionString = “Data Source=.SQLEXPRESS;Initial Catalog=Northwind; Integrated Security=SSPI;”;
catch(SqlException sqlError)
Console.WriteLine(“SQL exception occurred: {0}”, sqlError.Message);
catch(Exception generalError)
Console.WriteLine(“General exception occurred: {0}”, generalError.Message);
if(theConnection.State = ConnectionState.Open)

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s