How try-catch-finally block will be executed is discussed in the following Try-catch url.
Through the below program we come to know that finally block is always executed whether exception is handled or not.
C# program to release the database connection after completing the transaction.
C# code
using System;
using System.Data.SqlClient;
using System.Data;
class Program
{
static void Main(string[] args)
{
///Create the object of SqlConnection class to connect with database sql server
SqlConnection con = new SqlConnection();
try
{
con.ConnectionString = @"Data Source=VISWANATHA\SQLEXPRESS;Initial Catalog=EMPLOYEE;Integrated Security=True";
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = @"select EMPNO from emp ";
cmd.Connection = con;
//open database connection
con.Open();
Console.WriteLine("Connection open");
//execute the query
SqlDataReader sdr = cmd.ExecuteReader();
////Retrieve data from table and Display result
while(sdr.Read())
{
int id =(int) sdr["EMPNO"];
Console.WriteLine(id);
}
}
catch
{
Console.WriteLine("cannot open Connection");
}
finally
{
//close the connection
con.Close();
//relesae the resource (object of sql connection.) after closing connection with sql database server.
con = null;
}
}
}
Output
Connection open
7369
7499
7566
7654
7499
7521
7698
7782
7788
7839
7934
7902
7900
7876
7844
finally block can also work without catch block as shown below.
using System;
using System.Data.SqlClient;
using System.Data;
class Program
{
static void Main(string[] args)
{
///Create the object of SqlConnection class to connect with database sql server
SqlConnection con = new SqlConnection();
try
{
con.ConnectionString = @"Data Source=VISWANATHA\SQLEXPRESS;Initial Catalog=EMPLOYEE;Integrated Security=True";
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = @"select EMPNO from emp ";
cmd.Connection = con;
//open database connection
con.Open();
Console.WriteLine("Connection open");
//execute the query
SqlDataReader sdr = cmd.ExecuteReader();
////Retrieve data from table and Display result
while(sdr.Read())
{
int id =(int) sdr["EMPNO"];
Console.WriteLine(id);
}
}
finally
{
//close the connection
con.Close();
//release the resource (object of sql connection.) after closing connection with sql database server.
con = null;
}
}
}
Note:
At Least one catch block or finally block is mandatory after try block.