这段代码可能导致indexoutorange异常的原因是什么?

本文关键字:异常 indexoutorange 是什么 段代码 代码 | 更新日期: 2023-09-27 18:16:01

最近,我在一个特定的方法中得到了一个indexoutorange异常。此函数中的新代码读取"csv"文件(重命名为扩展名为"csv"的.txt文件)并对其进行解析;因此,它必须是特定于该异常的代码,否则就是引发该异常的数据本身。

但它显然不在插入数据库上,因为我在插入发生的catch块中添加了MessageBox.Show(),我从未看到过它。

public bool PopulatePlatypusItemsListAndInsertIntoPlatypusItemsTable(frmCentral fc)
{
    const int Platypus_ID_OFFSET = 0;
    const int Platypus_ITEM_ID_OFFSET = 1;
    const int ITEM_ID_OFFSET = 2;
    const int PACKSIZE_OFFSET = 3;
    bool ret = false;
    try
    {
        string dSQL;
        bool First = true;
        if (File.Exists(csvFilePathName))
        {
            int fzz = 0;
            dSQL = "DELETE FROM PlatypusItems";
            try
            {
                dbconn.DBCommand(dSQL, true);
            }
            catch
            {
                frmCentral.listboxMessage.TopIndex = frmCentral.listboxMessage.Items.Add(Convert.ToString(++frmCentral.lstMessageCount) +
                                                                                         ". Error processing PlatypusItem data from server");
            }
            SqlCeConnection conn = dbconn.GetConnection();
            if (conn != null && conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            SqlCeCommand cmd = conn.CreateCommand();
            cmd.CommandText = "INSERT INTO PlatypusItems ( PlatypusID, PlatypusItemID, ItemID, PackSize) VALUES (?, ?, ?, ?)";
            if (!ret) 
            {
                ret = true;
            }
            PlatypusItem DuckbillItm = new PlatypusItem();
            string thisLine;
            string[] arrLine;
            using (StreamReader sr = new StreamReader(csvFilePathName)) 
            {
                while (sr.Peek() >= 0) 
                {
                    thisLine = sr.ReadLine();
                    arrLine = thisLine.Split(',');
                    DuckbillItm.PlatypusID = arrLine[Platypus_ID_OFFSET];
                    DuckbillItm.PlatypusItemID = arrLine[Platypus_ITEM_ID_OFFSET];
                    DuckbillItm.ItemID = arrLine[ITEM_ID_OFFSET];
                    DuckbillItm.PackSize = Convert.ToInt32(arrLine[PACKSIZE_OFFSET]);
                    PlatypusItemList.List.Add(DuckbillItm);
                    dSQL = "INSERT INTO PlatypusItems (PlatypusID, PlatypusItemID, ItemID, PackSize) VALUES (" + DuckbillItm.PlatypusID + ",'" +
                        DuckbillItm.PlatypusItemID + "','" + DuckbillItm.ItemID + "'," + DuckbillItm.PackSize + ")";
                    if (!First)
                    {
                        cmd.Parameters[0].Value = DuckbillItm.PlatypusID;
                        cmd.Parameters[1].Value = DuckbillItm.PlatypusItemID;
                        cmd.Parameters[2].Value = DuckbillItm.ItemID;
                        cmd.Parameters[3].Value = DuckbillItm.PackSize.ToString();
                    }
                    if (First)
                    {
                        cmd.Parameters.Add("@PlatypusID", DuckbillItm.PlatypusID);
                        cmd.Parameters.Add("@PlatypusItemID", DuckbillItm.PlatypusItemID);
                        cmd.Parameters.Add("@ItemID", DuckbillItm.ItemID);
                        cmd.Parameters.Add("@PackSize", DuckbillItm.PackSize);
                        cmd.Prepare();
                        First = false;
                    }
                    if (frmCentral.CancelFetchInvDataInProgress)
                    {
                        return false;
                    }
                    try
                    {
                        // testing with these reversed: - either way, get the IndexOutOfRange exception...
                        //dbconn.DBCommand(cmd, dSQL, true);
                        dbconn.DBCommand(cmd, cmd.CommandText, true); //<-- If this works as well or better, dSQL is only there for the progress updating code below
                        // the first line is the legacy code; the second seems more sensible to me; both seem to work
                    }
                    catch (Exception x)
                    {
                        MessageBox.Show(string.Format("dbcommand exc message = {0}; PlatypusID = {1}; PlatypusItemID = {2}; ItemID = {3}; PackSize = {4}",      
                    x.Message, DuckbillItm.PlatypusID, DuckbillItm.PlatypusItemID, DuckbillItm.ItemID, DuckbillItm.PackSize));//TODO: Remove
                        frmCentral.listboxMessage.TopIndex =
                            frmCentral.listboxMessage.Items.Add(Convert.ToString(++frmCentral.lstMessageCount) +
                            ". Error processing Platypus Item data from server");
                    }
                    fzz += dSQL.Length; //<-- tried commenting this weird code out, but still get IndexOutOfRangeException
                    if (fzz > fc.ProgressChangedIndex)
                    {
                        fc.ProgressChangedIndex = fzz + fc.ProgressChangedIncrement;
                        if (((frmCentral.ProgressBar.progressBar1.Maximum/4) + (fzz*3) < frmCentral.ProgressBar.progressBar1.Maximum) &&
                            ((frmCentral.ProgressBar.progressBar1.Maximum/4) + (fzz*3) > frmCentral.ProgressBar.progressBar1.Value))
                        {
                            frmCentral.ProgressBar.progressBar1.Value = (frmCentral.ProgressBar.progressBar1.Maximum/4) + (fzz*3);
                            frmCentral.ProgressBar.progressBar1.Refresh();
                        }
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        duckbilledPlatypiRUs.ExceptionHandler(ex, "PlatypusItemFile.PopulatePlatypusItemsListAndInsertIntoPlatypusItemsTable");
    }
    return ret;
}

我知道这段代码是不同风格的古怪组合;好的代码是我的,奇怪的代码是遗留的(g,d&r)

当然,我可以这样做,来扫除地毯下的灰尘:

catch (Exception ex)
{
    if (ex.Message.IndexOf("IndexOutOfRange") < 0)
    {
        duckbilledPlatypiRUs.ExceptionHandler(ex, "PlatypusItemFile.PopulatePlatypusItemsListAndInsertIntoPlatypusItemsTable"); 
    }
}

…但是我不知道这个IndexOutOfRangeException是否真的是一个严重的问题,它在这个应用程序的内部造成了混乱。

更新

我添加了以下代码:

if (arrLine[PLATYPUS_ID_OFFSET].Length > 10) //TODO: Remove?
            {
                                MessageBox.Show(string.Format("PLATYPUS_ID_OFFSET length should be 10; was {0}", arrLine[PLATYPUS_ID_OFFSET].Length));
                                arrLine[PLATYPUS_ID_OFFSET] = arrLine[PLATYPUS_ID_OFFSET].Substring(0, 10);
                            }
                            if (arrLine[PLATYPUS_ITEM_ID_OFFSET].Length > 19)
                            {
                                MessageBox.Show(string.Format("PLATYPUS_ITEM_ID_OFFSET length should be 19; was {0}", arrLine[PLATYPUS_ID_OFFSET].Length));
                                arrLine[PLATYPUS_ITEM_ID_OFFSET] = arrLine[PLATYPUS_ITEM_ID_OFFSET].Substring(0, 19);
                            }
                            if (arrLine[ITEM_ID_OFFSET].Length > 19)
                            {
                                MessageBox.Show(string.Format("ITEM_ID_OFFSET length should be 19; was {0}", arrLine[PLATYPUS_ID_OFFSET].Length));
                                arrLine[ITEM_ID_OFFSET] = arrLine[ITEM_ID_OFFSET].Substring(0, 19);
                            }

…我从来没有见过那些MessageBox.Show()s,所以我想这不是三个字符串值造成的问题;可能是int (PackSize)。PackSize永远不会大于Int32允许的;在。net 1.1中有等价的TryParse()吗?

更新2

确实从这里的异常中看到了" indexoutorange ",但从未看到MessageBox.Show()s:

try
{
    thisLine = sr.ReadLine();
    arrLine = thisLine.Split(',');
    if (arrLine[PLATYPUS_ID_OFFSET].Length > 10) //TODO: Remove?
    {
        MessageBox.Show(string.Format("PLATYPUS_ID_OFFSET length should be 10; was {0}", arrLine[PLATYPUS_ID_OFFSET].Length));
        arrLine[PLATYPUS_ID_OFFSET] = arrLine[PLATYPUS_ID_OFFSET].Substring(0, 10);
    }
    . . .
    DuckbillItm.PLATYPUSID = arrLine[PLATYPUS_ID_OFFSET];
    DuckbillItm.PLATYPUSItemID = arrLine[PLATYPUS_ITEM_ID_OFFSET];
    DuckbillItm.ItemID = arrLine[ITEM_ID_OFFSET];
    DuckbillItm.PackSize = Convert.ToInt32(arrLine[PACKSIZE_OFFSET]);
}
catch (Exception exc)
{
    MessageBox.Show(exc.Message);
}

3

更新毕竟,这是糟糕的数据;有些行有四个逗号,而不是预期的三个。所以,我只是删除了这些行(在添加代码来检查数组的每个元素的大小,并在此之前修剪它们之后),它运行得很好。

我最初的猜测:如果你输入的。csv文件是坏的,可能其中的arrLine[...]行(例如DuckbillItm.PlatypusID = arrLine[Platypus_ID_OFFSET])会导致这个问题。进行调试构建并将断点放在catch处理程序上,并告诉我们"ex.StackTrace"是什么。

这段代码可能导致indexoutorange异常的原因是什么?