Junior — Middle
Kas toimub, kui programmis tekib väljaheitmise erand, mis on seotud massiivi piiride ületamisega?
sobes.tech AI
Vastus AI-lt
When in C# you attempt to access an array element using an index that is outside the allowed range (less than 0 or greater than or equal to the array length), the runtime environment 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 unexpectedly. 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("Index out of array bounds");
}
This way, the exception helps to identify data access errors and prevents unpredictable behavior of the program.