HOME RESOURCES PLACEMENTS CONTACT FEEDBACK SUBSCRIBE
QUICK LINKS .NET Articles
.NET Training Tutorial
HR Interview Questions
.NET Interview Questions
SQL Interview Questions
JAVA Interview Questions

Exception Handling in C# : Part 2
Let us understand the usage of finally block with an example.
  1. The program below will read the firstnames of the employee from the employee table and print them to the screen.
  2. In the program we retrieve the data from the employee table by opening the connection, loop thru the datareader and display the names and finally close the connection.
  3. We are closing the connection in the try block. If an exception occurs, when reading the data, or during displaying the data the control will be immediately transfered to the catch block without executing con.Close() method. The database connection is left open and the program is terminated.
  4. Database connections are very valuable resources. You must close all the open connections as soon as you are done reading the data. Otherwise the scalability of the application is negatively affected.
  5. When open files and read them using file streams, the file streams have to be closed as well. Filestreams and Database connections are valuable resources and need to be closed in timely manner irrespective of wheather your program successfully executed or terminated with an exception.
  6. So the ideal place to have the code that closes database connections or file streams is the finally block. Finally block is guaranteed to execute irrespective of wheather the program successfully ran or terminated with an exception. Finally blocks are used to clean up valuable resources. Finally block is optional.

using System;

using System.Data;

using System.Data.SqlClient;

public class MainClass

{

    public static void Main()

    {

        SqlConnection con;

        try

        {

            string ConnectionString = "data source=.;database=Northwind;integrated security=SSPI";

            con = new SqlConnection(ConnectionString);

            SqlCommand cmd = new SqlCommand("Select FirstName from employee", con);

            con.Open();

            SqlDataReader rdr = cmd.ExecuteReader();

            while (rdr.Read())

            {

                Console.WriteLine(rdr["FirstName"].ToString());

            }

            //Always include resource clean up code in finally block

            //The below line will never be executed if an exception occurs

            //con.Close();

        }

        catch (Exception Ex)

        {

            Console.WriteLine(Ex.Message);

        }

        finally

        {

            con.Close();

        }

    }

}

System Exception Vs Application Exceptions
In general there are 2 broad classifications of exceptions.
  • System Exceptions : All .NET defined exceptions are examples of System Exceptions. DivideByZeroException,OverflowException etc.. are examples of System Exceptions. All predefined .NET exceptions derive directly or indirectly from SystemException class. SystemException class derives from Exeception class.
  • Application Exceptions : If none of the exceptions available in .NET, are useful for your program, you can create userdefined exceptions. Userdefined exceptions usually derive from ApplicationException class. ApplicationException class derive from Exception class.
Below is an example that shows how to create a userdefined ApplicationException.

using System;

class UserDefinedException : ApplicationException

{

    public UserDefinedException()

    {

        Console.WriteLine("User Defined Exception");

    }

}

class MainClass

{

    public static void Main()

    {

        try

        {

            throw new UserDefinedException();

        }

        catch (UserDefinedException e)

        {

            Console.WriteLine(e.Message);

        }

    }

}

Take awaya key points about exception handling
  • All exceptions directly or indirectly derive from System.Exception base class.
  • It is a compile time error to have try block in isolation. A try block should be followed by a catch or finally block.
  • A single try block can have multiple catch blocks but only one finally block.
  • We use the throw keyword to raise exceptions programtically.
Further Reading
Other related articles

Njoy Programming
   ByPrasad Cherukuri