C# में IndexOutOfRangeException पकड़ना
IndexOutOfRangeException तब थ्रो होता है जब आप एरे/कलेक्शन की वैध सीमा (0 से Length-1) के बाहर इंडेक्स एक्सेस करते हैं।
उदाहरण: एक्सेप्शन जनरेट करना
int[] n = new int[5] { 66, 33, 56, 23, 81 };
// वैध इंडेक्स: 0,1,2,3,4
for (int j = 0; j < 10; j++) {
Console.WriteLine($"Element[{j}] = {n[j]}"); // j=5 पर एक्सेप्शन
}
आउटपुट (एक्सेप्शन)
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.
सही तरीका: try-catch से पकड़ें
using System;
class Program {
static void Main() {
int[] n = { 66, 33, 56, 23, 81 };
try {
for (int j = 0; j < 10; j++) {
Console.WriteLine($"Element[{j}] = {n[j]}");
}
}
catch (IndexOutOfRangeException ex) {
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine("Array bounds: 0 to " + (n.Length - 1));
}
catch (Exception ex) {
Console.WriteLine($"Unexpected error: {ex.Message}");
}
}
}
आउटपुट
Element[0] = 66 Element[1] = 33 Element[2] = 56 Element[3] = 23 Element[4] = 81 Error: Index was outside the bounds of the array. Array bounds: 0 to 4
बेहतर दृष्टिकोण: बाउंड्स चेक करें (एक्सेप्शन से बचें)
// सुरक्षित एक्सेस
if (index >= 0 && index < arr.Length) {
var value = arr[index];
}
// या C# 8+ रेंज ऑपरेटर
var slice = arr[2..5]; // इंडेक्स 2,3,4 (सुरक्षित, आउट-ऑफ-रेंज पर एक्सेप्शन नहीं)
मुख्य बिंदु
- हमेशा लूप कंडीशन में
arr.Lengthउपयोग करें, हार्डकोडेड नंबर नहीं। foreachलूप इंडेक्स एरर से बचाता है।- एक्सेप्शन हैंडलिंग महंगी है; रक्षात्मक चेक (
if) प्रीफर करें। Array.GetValue(index)भी एक्सेप्शन थ्रो करता है।