Dealing with Exceptions in ADO.NET

Exceptions are handled using the try, catch and finally blocks.
The try block contains code that raises an exception. The exceptions that are raised in the try block are caught in one or more appropriate catch blocks.
A finally block is executed whether or not an exception occurs. Hence, it is particularly useful for cleanup operations. The purpose of a finally statement is to ensure that the necessary cleanup of objects, usually objects that are holding external resources, happens immediately, even if an exception is thrown.

Below is a well written code for ADO.NET usage.

Example:
{
   string connectionString = ...; // Some database connection string
   SqlConnection connection = null;
   try
   {
          connection = new SqlConnection(connectionString);
          connection.Open();
          //Some query executing codes
         //a return statement can exists here
   }
   catch (Exception ex)
   {
      //this block executes only when an exception occurs
      //Some exception handling code
      //a return statement can exist here
   } 
   finally
   {
            //finally code always executes whether or not you have exception
            //always close the connection object in finally
            //always dispose or free the resources n finally
           connection.Close();
   }
}

Ebook Download
View all
Learn
View all