Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to capture index out of range exception in C#?
The IndexOutOfRangeException occurs when you try to access an array element with an index that is outside the bounds of the array. This is a common runtime exception in C# that can be captured using try-catch blocks.
Understanding Array Bounds
Arrays in C# are zero-indexed, meaning the first element is at index 0. If an array has 5 elements, the valid indices are 0, 1, 2, 3, and 4. Accessing index 5 or higher will throw an IndexOutOfRangeException.
Syntax
Following is the syntax for catching IndexOutOfRangeException −
try {
// array access code
array[index] = value;
} catch (IndexOutOfRangeException ex) {
// handle the exception
Console.WriteLine("Index out of range: " + ex.Message);
}
Example with Exception Handling
The following example demonstrates how to capture and handle IndexOutOfRangeException −
using System;
class MyArray {
static void Main(string[] args) {
try {
int[] n = new int[5] {66, 33, 56, 23, 81};
// This loop tries to access indices 0-9, but array only has indices 0-4
for (int j = 0; j < 10; j++) {
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
} catch (IndexOutOfRangeException e) {
Console.WriteLine("Exception caught: " + e.Message);
}
}
}
The output of the above code is −
Element[0] = 66 Element[1] = 33 Element[2] = 56 Element[3] = 23 Element[4] = 81 Exception caught: Index was outside the bounds of the array.
Prevention Using Length Property
The best practice is to prevent the exception by checking array bounds using the Length property −
using System;
class SafeArrayAccess {
static void Main(string[] args) {
int[] numbers = new int[5] {10, 20, 30, 40, 50};
Console.WriteLine("Safe array access:");
for (int i = 0; i < numbers.Length; i++) {
Console.WriteLine("Element[{0}] = {1}", i, numbers[i]);
}
// Attempting to access beyond bounds safely
int index = 7;
if (index < numbers.Length) {
Console.WriteLine("Element[{0}] = {1}", index, numbers[index]);
} else {
Console.WriteLine("Index {0} is out of bounds. Array length is {1}", index, numbers.Length);
}
}
}
The output of the above code is −
Safe array access: Element[0] = 10 Element[1] = 20 Element[2] = 30 Element[3] = 40 Element[4] = 50 Index 7 is out of bounds. Array length is 5
Common Scenarios
IndexOutOfRangeException commonly occurs in the following scenarios −
-
Using incorrect loop conditions (e.g.,
i instead ofi ) -
Accessing arrays with negative indices
-
Using hardcoded indices without checking array size
-
Off-by-one errors in calculations
Example with Multiple Exception Types
using System;
class MultipleExceptions {
static void Main(string[] args) {
int[] data = {5, 10, 15, 20};
try {
Console.WriteLine("Accessing valid index: " + data[2]);
Console.WriteLine("Accessing invalid index: " + data[10]);
} catch (IndexOutOfRangeException ex) {
Console.WriteLine("IndexOutOfRangeException: " + ex.Message);
} catch (Exception ex) {
Console.WriteLine("General exception: " + ex.Message);
}
}
}
The output of the above code is −
Accessing valid index: 15 IndexOutOfRangeException: Index was outside the bounds of the array.
Conclusion
The IndexOutOfRangeException can be captured using try-catch blocks, but prevention is better than handling. Always use the array's Length property to ensure indices are within valid bounds before accessing array elements.
