How to throw an exception in C#

1 Answer

0 votes
using System;

public class Number {
    int[] arr = { 4, 7, 0, 6, 1, 8 };
    
    public int GetNumber(int i) {
        if (i < 0 || i >= arr.Length) {
            throw new IndexOutOfRangeException();
        }
        return arr[i];
    }
}


public class Program {
   public static void Main() {
      var o = new Number();
      
      try {
          Console.WriteLine(o.GetNumber(3));
          Console.WriteLine(o.GetNumber(99));
      }
      catch (IndexOutOfRangeException ex) {
         Console.WriteLine(ex.GetType().Name);
      }
   }
}




/*
run

6
IndexOutOfRangeException

*/

 



answered Nov 27, 2020 by avibootz

Related questions

1 answer 251 views
251 views asked Nov 27, 2020 by avibootz
1 answer 246 views
2 answers 277 views
277 views asked Oct 21, 2022 by avibootz
1 answer 298 views
298 views asked Jan 3, 2016 by avibootz
2 answers 467 views
1 answer 340 views
...