ARTICLE

Exception Handling in C#

Posted by Rekha Singh Articles | Exception Handling C# August 19, 2009
In this article we will see exception handling technique in C#.
Reader Level:

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);
            }
        }
    }

}


 

Login to add your contents and source code to this article
comments
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
HTML 5 + JQUERY CONTROLS
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
HTML 5 + JQUERY CONTROLS