Junior — Middle
Can you explain what happens when an array out-of-bounds exception occurs in a program?
sobes.tech AI
Answer from AI
In C#, when attempting to access an array element by index that is outside the valid range (less than 0 or greater than or equal to the array length), the runtime throws an IndexOutOfRangeException. This exception indicates that the program is trying to access a non-existent array element.
If this exception is not caught by a try-catch block, the program will terminate abruptly. To prevent this, you can use exception handling or check the index before accessing the array:
int[] numbers = {1, 2, 3};
int index = 5;
if (index >= 0 && index < numbers.Length)
{
Console.WriteLine(numbers[index]);
}
else
{
Console.WriteLine("Array index out of range");
}
Thus, the exception helps identify data access errors and prevents unpredictable program behavior.