【问题标题】:Program is not throwing ArgumentOutOfRange Exception程序没有抛出 ArgumentOutOfRange 异常
【发布时间】:2019-10-24 13:51:38
【问题描述】:

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

        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 异常。 如果我希望异常类似于“请给出一个 0-5 之间的数字”,我应该怎么做? (使用try-catch方法)

【问题讨论】:

    标签: c# try-catch expectations


    【解决方案1】:

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

    除了@Ciubotariu Florin 是对的。

    【讨论】:

    • 你能解释一下你的意思吗?
    • 如果您需要在索引超出范围时得到错误消息“请给出一个介于 0-5 之间的数字”,那么只需在 int l=arr[k]; 之前写一个 if 语句,如下所示:if(k < 0 || k > 5) throw new ArgumentException("please give a number between 0-5");而不是使用 try-catch 块。这样你就可以更明确地表达你的意图。
    • 是的,我知道,我只是在尝试,因为这对我来说是一个新主题。
    【解决方案2】:

    IndexOutOfRangeExceptionArgumentOutOfRangeException 之间存在差异。 您必须改为捕获 IndexOutOfRangeException。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-21
      • 1970-01-01
      • 1970-01-01
      • 2011-12-12
      相关资源
      最近更新 更多