如何解决未处理的异常:ArumentOutOfRangeException

时间:2019-04-04 07:55:21

标签: c# indexoutofrangeexception

我正在尝试捕获未处理的异常,但仍会发生错误。我需要在哪里开始“尝试”,何时/如何进行? 这是我的代码:

            String allMarks = "";
            String toString1 = "";
            String toString2 = "";

            if (eventcounter.Count > 2)
            {
                allMarks = allMarks + eventcounter[0];

                for (int i = 0; i < eventcounter.Count; i++)
                {
                    toString1 = eventcounter[i].ToString();

                    for (int j = 1; j <= eventcounter.Count; j++)
                    {
                        try
                        {
                            toString2 = eventcounter[j].ToString();
                        }
                        catch (System.IndexOutOfRangeException)
                        {
                            Console.WriteLine("not enough elements to compare");
                            throw new System.ArgumentOutOfRangeException("Index parameter is out of range");
                        }

                        if (toString1 != toString2)//(eventcounter[i] != eventcounter[j])
                        {
                            allMarks = allMarks + eventcounter[j];
                            Console.WriteLine(allMarks);
                            //_sensorTextView3.Text = string.Format("Eventcounter: {0}", allMarks);
                        }
                    }
                }
               // _sensorTextView3.Text += allMarks;
            }

更新: 好的,我现在只使用一个循环,而不是两个循环,但是无论何时运行代码,仍然会发生错误

for (int i = 0; i < eventcounter.Count; i++)
                {
                    try
                    {
                        toString1 = eventcounter[i].ToString();
                        toString2 = eventcounter[i + 1].ToString();
                    }
                    catch (System.IndexOutOfRangeException)
                    {

                        throw new System.ArgumentOutOfRangeException("Index parameter is out of range");
                    }

                    if (toString1 != toString2)
                    {
                        allMarks = allMarks + eventcounter[i+1];
                        Console.WriteLine(allMarks);
                    }

1 个答案:

答案 0 :(得分:0)

eventcounter包含eventcounter.Count个元素,编号从0eventcounter.Count-1

使用

for (int j = 1; j <= eventcounter.Count; j++)

在某个时刻j将等于eventcounter.Count。由于元素编号范围是[0eventcounter.Count],因此尝试访问元素编号eventcounter.Count会抛出IndexOutOfRangeException