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 149 views
149 views asked Nov 27, 2020 by avibootz
1 answer 162 views
162 views asked Nov 27, 2020 by avibootz
2 answers 306 views
1 answer 214 views
2 answers 161 views
161 views asked Oct 21, 2022 by avibootz
1 answer 227 views
227 views asked Jan 3, 2016 by avibootz
1 answer 254 views
...