IndexOutOfRangeException ঘটে যখন আপনি অ্যারের সীমার বাইরে একটি সূচক সহ একটি উপাদান অ্যাক্সেস করার চেষ্টা করেন৷
ধরা যাক নিম্নলিখিতটি আমাদের অ্যারে। এতে ৫টি উপাদান আছে -
int [] n = new int[5] {66, 33, 56, 23, 81}; এখন আপনি যদি 5-এর বেশি সূচক সহ উপাদানগুলি অ্যাক্সেস করার চেষ্টা করেন, তাহলে IndexOutOfRange ব্যতিক্রম নিক্ষেপ করা হয় -
for (j = 0; j < 10; j++ ) {
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
} উপরের উদাহরণে, আমরা উপরের সূচক 5 অ্যাক্সেস করার চেষ্টা করছি, তাই নিম্নলিখিত ত্রুটিটি ঘটে -
System.IndexOutOfRangeException:সূচক অ্যারের সীমার বাইরে ছিল।
এখানে সম্পূর্ণ কোড −
উদাহরণ
using System;
namespace Demo {
class MyArray {
static void Main(string[] args) {
try {
int [] n = new int[5] {66, 33, 56, 23, 81};
int i,j;
// error: IndexOutOfRangeException
for (j = 0; j < 10; j++ ) {
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
Console.ReadKey();
} catch (System.IndexOutOfRangeException e) {
Console.WriteLine(e);
}
}
}
} আউটপুট
Element[0] = 66 Element[1] = 33 Element[2] = 56 Element[3] = 23 Element[4] = 81 System.IndexOutOfRangeException: Index was outside the bounds of the array. at Demo.MyArray.Main (System.String[] args) [0x00019] in <6ff1dbe1755b407391fe21dec35d62bd>:0
কোডটি একটি ত্রুটি তৈরি করবে −
System.IndexOutOfRangeException −Index was outside the bounds of the array.