C# IndexOutOfRangeException
Program.cs
using System;
namespace Kodingwindow
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string[] s = { "Mango", "Pineaple", "Grapes", "Banana", "Apple", "Strawberry" };
            Console.WriteLine("Array Length: " + s.Length);
            Console.WriteLine("First Element: " + s[0]);
            Console.WriteLine("Last Element: " + s[5]);
            Console.WriteLine(s[6]);
        }
    }
}
Output
kodingwindow@kw:~/csharp$ dotnet run
Array Length: 6
First Element: Mango
Last Element: Strawberry
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
    at Program.
$(String[] args) in /home/kodingwindow/csharp/Program.cs:line 5 kodingwindow@kw:~/csharp$
C# program to handle the IndexOutOfRangeException
Program.cs
string[] s = { "Mango", "Pineaple", "Grapes", "Banana", "Apple", "Strawberry" };
Console.WriteLine("Array Length: " + s.Length);
Console.WriteLine("First Element: " + s[0]);
Console.WriteLine("Last Element: " + s[5]);
try
{
    Console.WriteLine(s[6]);
}
catch (IndexOutOfRangeException)
{
    Console.WriteLine("Requested element not found");
}
Output
kodingwindow@kw:~/csharp$ dotnet run
Array Length: 6
First Element: Mango
Last Element: Strawberry
Requested element not found 
kodingwindow@kw:~/csharp$ 
Advertisement