Exception Handling in C#


Exception handling is an in built mechanism in .NET framework to detect and handle runtime errors. The .NET framework contains lots of standard exceptions.

The exceptions are anomalies that occur during the execution of a program.

"Exception is a runtime error which arises because of abnormal conditions in a condition in a sequence."

C# provides three keywords try, catch and finally to do exception handling. The try encloses the statements that might throw an exception whereas catch handles exception if one exists. The finally can be used for doing any clean up process.

The general form of try-catch-finally in c# is shown below:

try
{
    // Statements which can cause an exception
}
catch(Type x)
{
    // Statements for handling the exception
}
finally
{
    // Any Cleanup Code
}

Example of Exception Handling:

using
System;
namespace
ConsoleApplication1
{
    class main
    {
        public static void Main()
        {
            int[] a = new int[5];
            int i;
            try
            {
                for (i = 0; i < 7; i++)
                {
                    a[i] = Convert.ToInt32(Console.ReadLine());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Please Check The Error Limits...");
            }
            for (i = 0; i < 5; i++)
            {
                Console.WriteLine("Array Element Is " + a[i]);
            }
        }
    }

}

Program to divide two numbers using Exception Handling:

using
System;
using
System.Collections.Generic;
using
System.Text;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            int x, y, z = 0;
            try
            {
                Console.WriteLine("Enter The Value of X");
                x = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Enter The Value of Y");
                y = Convert.ToInt32(Console.ReadLine());
                z = x / y;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                Console.WriteLine("The Division is : " + z);
            }
        }
    }

}


 

Up Next
    Ebook Download
    View all
    Learn
    View all