c# – How do I handle IndexOutOfRangeException?

Question:

The assignment specifies to create 2 classes: in the 1st, create and initialize an array of 10 int elements, a default constructor and an indexer; in the 2nd class – Main, in which to demonstrate the situation of the array out of bounds. You need to catch and handle the exception in the indexer . Help, how to catch the exception?

    class B
{
    private int[] a = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    public int this[int i]
    {
        get { if (i >= 0 && i <= 10) return a[i]; else throw new IndexOutOfRangeException(); }
        set { if (i >= 0 && i <= 10) a[i] = value; else throw new IndexOutOfRangeException(); }
    }

}

class MainClass
{
    public static void Main(string[] args)
    {
            B bi = new B();
            for (int i = 0; i <= 10; i++)
            {Console.WriteLine(bi[i]);}
    }
}

Answer:

get 
{
  try 
  {
    return a[i];
  }
  catch(IndexOutOfRangeException ex) 
  {
    // handle exception
    return 0;
  }
}
Scroll to Top