How to catch index out of range exception in C#?

WBOY
Release: 2023-08-25 22:13:09
forward
1786 people have browsed it

How to catch index out of range exception in C#?

IndexOutOfRangeException occurs when you try to access an element whose index is outside the range of the array.

Suppose the following is our array. It has 5 elements -

int [] n = new int[5] {66, 33, 56, 23, 81};
Copy after login

Now if you try to access an element with index greater than 5 then IndexOutOfRange exception will be thrown -

for (j = 0; j < 10; j++ ) {
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
Copy after login

In the above example we are trying to access the above Index 5, so the following error occurs -

System.IndexOutOfRangeException: Index is outside the range of the array.

This is the complete code -

Example

Live demonstration

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);
         }
      }
   }
}
Copy after login

Output

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
Copy after login

The code will produce an error-

System.IndexOutOfRangeException &minus;Index was outside the bounds of the array.
Copy after login

The above is the detailed content of How to catch index out of range exception in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!