在出现异常后继续执行循环,并将所有错误存储在字符串生成器对象中

本文关键字:字符串 存储 有错误 对象 异常 继续 循环 执行 | 更新日期: 2023-09-27 18:21:29

我正在读取excel文件,并且随时读取字段具有错误值的执行被停止并继续到捕获部分。(例如在dateTime列中有一个字符串)我希望能够完成循环并存储所有错误在字符串生成器对象中遇到的消息没有停止处决我不希望用户在遇到错误时更正输入文件。字符串生成器对象应该显示文件中的所有错误。

请问我怎样才能做到这一点?我试着继续,但运气不好。

public void  testThis()
{
    try
    {
        for (int rowNumber = startRow + 1; rowNumber <= currentWorkSheet.Dimension.End.Row; rowNumber++)
        // read each row from the start of the data (start row + 1 header row) to the end of the spreadsheet.
        {
            object col1Value = currentWorkSheet.Cells[rowNumber, 1].Value;
            object col2Value = currentWorkSheet.Cells[rowNumber, 2].Value;
            object col3Value = currentWorkSheet.Cells[rowNumber, 3].Value;
            object col4Value = currentWorkSheet.Cells[rowNumber, 4].Value;
            if ((col1Value != null && col2Value != null))
            {
                exampleDataList.Add(new PersonalData
                {
                    firstname = col1Value.ToString(),
                    lastname = col2Value.ToString(),
                    currentDate = col3Value == null ? DateTime.MinValue : Convert.ToDateTime(col3Value),
                    mySalary = col4Value == null ? 0 : Convert.ToInt32(col4Value)
                });
            }
        }
    }
    catch(Exception Exception)
    {
        //continue.. do not stop
    }
}

在出现异常后继续执行循环,并将所有错误存储在字符串生成器对象中

Try..Catch块移动到For循环中

StringBuilder sb = new StringBuilder();
for (int rowNumber = startRow + 1; rowNumber <= currentWorkSheet.Dimension.End.Row; rowNumber++)
        // read each row from the start of the data (start row + 1 header row) to the end of the spreadsheet.
{
    try
    {
        object col1Value = currentWorkSheet.Cells[rowNumber, 1].Value;
        object col2Value = currentWorkSheet.Cells[rowNumber, 2].Value;
        object col3Value = currentWorkSheet.Cells[rowNumber, 3].Value;
        object col4Value = currentWorkSheet.Cells[rowNumber, 4].Value;
        if ((col1Value != null && col2Value != null))
        {
            exampleDataList.Add(new PersonalData
            {
                firstname = col1Value.ToString(),
                lastname = col2Value.ToString(),
                currentDate = col3Value == null ? DateTime.MinValue : Convert.ToDateTime(col3Value),
                mySalary = col4Value == null ? 0 : Convert.ToInt32(col4Value)
            });
        }
    }      
    catch (Exception e)
    {
         //log exception here
        sb.AppendFormat("{0}: {1}{2}",rowNumber, e.Message, Environment.NewLine);           
    }
} 
//convert the StringBuilder into the final string object
string allMessages = sb.ToString();

问题是必须将try/catch放在for内部,而不是外部!

那么在接球的时候你可以用还是不用继续,没关系!

在进入for循环之前和之后创建StringBuilder距离。您可以使用.ToString() 显示其内容