How to close the connection using finally block in ASP.Net c#?

How to close the connection using finally block in ASP.Net c#?, someone asked me to explain?

In this article we will discuss, to close the connection using finally block .In .net exception is handled by using following keywords such as try, catch, finally and throw.

In connections should be opened as late as possible, and should be closed soon as possible. Closing the connection in the finally block for better performance and scalability.


protected void Page_Load(object sender, EventArgs e)
            if (!IsPostBack)
                //Create the connection object
                SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ShoppingZone"].ConnectionString); ;
                    // Pass the connection to the command object, so the command object knows on which
                    // connection to execute the command
                    SqlCommand cmd = new SqlCommand("Select * from employee", connection);
                    // Open the connection. Otherwise you get a runtime error. An open connection is
                    // required to execute the command
                    GridView1.DataSource = cmd.ExecuteReader();
                catch (Exception ex)
                   // Handle Exceptions, if any
                    // The finally block is guarenteed to execute even if there is an exception.
                    //  This ensures connections are always properly closed.

Post your comments / questions