C# - IndexOutOfRange Exception Example

Learn about the IndexOutOfRange exception and demonstrating the example of IndexOutOfRange exception in C#. By Nidhi Last updated : April 03, 2023

IndexOutOfRange Exception

Here, we are demonstrating the IndexOutOfRange exception. Here, we will access the element of the array from the index which is out of bounds of the array then the program will exception that will be caught in the "catch" block.

C# program to demonstrate IndexOutOfRange exception

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

//C# - IndexOutOfRange Exception Example

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.

C# Exception Handling Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.