C# program to demonstrate IndexOutOfRange exception

Here, we are going to learn about the IndexOutOfRange exception and demonstrating the example of IndexOutOfRange exception in C#.
Submitted by Nidhi, on September 16, 2020

Here we demonstrate the index out of bounds 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.

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.

C# Exception Handling Programs »


ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.