Q:

C# program to demonstrate IndexOutOfRange exception

belongs to collection: C# Exception Handling Programs

0

C# program to demonstrate IndexOutOfRange exception.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

The source code to demonstrate the IndexOutOfRange exception is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# Program to Demonstrate IndexOutOfRange Exception

using System;

class ExceptionDemo
{
    static void Main(string[] args)
    {
        int[] intArray = new int[5] { 50,40,30,20,10 };
        int iLoop   = 0;
        int sum     = 0;

        try
        {
            for (iLoop = 0; iLoop <= 5; iLoop++)
            {
                sum += intArray[iLoop];
            }
            Console.WriteLine("Sum of array elements:" + sum);
        }
        catch (IndexOutOfRangeException e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

Output:

Index was outside the bounds of the array.
Press any key to continue . . .

Explanation:

In the above program, we created a class ExceptionDemo that contain the Main() method. In the Main() method, we created an array of integers that contains 5 elements. Here we also created two more variables iLoop and sum initialized with 0.

try
{
    for (iLoop = 0; iLoop <= 5; iLoop++)
    {
        sum += intArray[iLoop];
    }
    Console.WriteLine("Sum of array elements:" + sum);
}
catch (IndexOutOfRangeException e)
{
    Console.WriteLine(e.Message);
}

In the above code, we accessed the element at index 5, but the highest index of the array is 4. Then the program generated exception IndexOutOfRangeException that will be caught in the "catch" block and then print the exception message using the "Message" property on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# program to demonstrate DivideByZeroException ex... >>