程序没有抛出 ArgumentOutOfRange 异常

Program is not throwing ArgumentOutOfRange Exception

我有一个简单的程序,它从用户那里获取一个数字,returns 位于数组中 position/index 处的数字。但是,如果给定的数字不在索引范围内,则会抛出异常。 这是我的代码:

        int[] arr = { 1, 2, 3, 4, 5, 6 };    
            Console.WriteLine("input int");
            int k = int.Parse(Console.ReadLine());
            Console.WriteLine("before");
            try
            {
                double n = 5 / k;
                Console.WriteLine(n);
            int l=arr[k];
            Console.WriteLine(l);
            }
            catch (DivideByZeroException)
            {

                throw new ArgumentException("you cant divid by 0!");

            }
        catch (ArgumentOutOfRangeException)
        {

            throw new ArgumentException("please give a number between 0-5");

        }
        catch (Exception)
        {

            throw new ArgumentException("something went worng, please try again");

        }
        finally
            {
                Console.WriteLine("after");
                Console.WriteLine("process compited!");
            }

但是问题是,如果输入的数字是7,不在范围内,就会显示ArgumentOutOfRangeException异常。 如果我希望 Exception 像 "please give a number between 0-5" 应该怎么办? (使用 try-catch 方法)

有区别IndexOutOfRangeException and ArgumentOutOfRangeException。 您必须改为捕获 IndexOutOfRangeException。

不要使用异常来指导您的应用程序逻辑流。如果索引对于您的数组来说不是太大,最好主动检查。此索引号是来自外部的输入,因此您有权在其上放置您认为合适的任何防护装置。

除此之外@Ciubotariu Florin 是对的。