The task states to create 2 classes: in the 1st, create and initialize an array of 10 elements of type int, the default constructor and the indexer; in the 2nd class - Main, in which to demonstrate the situation of going beyond the boundaries of the array. It is necessary to intercept and process an 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]);} } } 
  • For good, such exceptions do not need to be handled, if this exception occurs - it means an error in the program. Well, if only as a teaching example ... - Andrew NOP

2 answers 2

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

    Well, if you need to "Catch and handle the need for an exception in the indexer.", Then you can do this:

     class ThingIndexer { private string[] _words; //ctor public ThingIndexer() { _words = new string[] { "один", "два", "три", "четыре", "пять", "шесть", "семь", "восемь", "девять", "десять" }; } public string this[int index] { get { try { return _words[index]; } catch (IndexOutOfRangeException) { return "Ошибка в индексе"; } } } } class MainClass { private int _start; private int _end; //ctor public MainClass(int start = 0, int end = 1) { _start = start; _end = end; } public IEnumerable<string> GetNumbers() { ThingIndexer tIndexer = new ThingIndexer(); for (int i = _start; i < _end; i++) { yield return tIndexer[i]; } } } class Program { static void Main(string[] args) { MainClass mc = new MainClass(4, 15); foreach (var item in mc.GetNumbers()) { Console.WriteLine(item); } Console.ReadKey(); } } 

    As a result, we get:

    five six seven eight nine ten Error in the index Error in the index Error in the index Error in the index Error in the index

    PS for your case: ... to initialize an array of 10 elements of type int, ... you need to remake quite a bit :)