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 242 views
242 views asked Nov 27, 2020 by avibootz
1 answer 244 views
2 answers 267 views
267 views asked Oct 21, 2022 by avibootz
1 answer 294 views
294 views asked Jan 3, 2016 by avibootz
2 answers 454 views
1 answer 339 views
...