C# Program for Indexoutofrangeexception Handling

Below is an example of exception handling which includes indexoutofrangeexception….
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
    class arrayoutofindex
    {
        public void calculatesum()
        {
            int sum=0;
            int [] number= new int[5] {1,2,3,4,5};
            try
            {
                for (int init =1; init <=5; init++)
                {
                    sum= sum +  number[init];
                }
                Console.WriteLine(“The sum of the array is:” + sum);
            }
            catch (IndexOutOfRangeException e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
    class classmain
    {
        static void Main(string [] args)
    {
        arrayoutofindex obj = new arrayoutofindex();
        obj.calculatesum();
        Console.ReadLine();
    }
}
}

Add Comment