How to throw an exception from main program (class with main) in C#

1 Answer

0 votes
using System;

public class Program {
    static int[] arr = { 4, 7, 0, 6, 1, 8 };
    
    static int GetNumber(int i) {
        if (i < 0 || i >= arr.Length) {
            throw new IndexOutOfRangeException();
        }
        return arr[i];
    }
    public static void Main() {
      try {
          Console.WriteLine(GetNumber(4));
          Console.WriteLine(GetNumber(99));
      }
      catch (IndexOutOfRangeException ex) {
         Console.WriteLine(ex.GetType().Name);
      }
   }
}




/*
run

1
IndexOutOfRangeException

*/

 



answered Nov 27, 2020 by avibootz

Related questions

1 answer 141 views
141 views asked Nov 27, 2020 by avibootz
1 answer 152 views
152 views asked Nov 27, 2020 by avibootz
2 answers 295 views
1 answer 207 views
2 answers 150 views
150 views asked Oct 21, 2022 by avibootz
1 answer 219 views
219 views asked Jan 3, 2016 by avibootz
1 answer 246 views
...