【问题标题】:datareader fails but does not raise exception c#datareader 失败但不引发异常 c#
【发布时间】:2015-12-27 20:34:25
【问题描述】:

我是 C# 的新手,我发现一些异常处理或缺少异常处理令人费解。我试图捕捉这些异常,但它们没有被捕捉到,我不明白为什么。代码将在异常之后出现,并且异常之后的所有内容都将被忽略,执行的下一行将是表单的绘制事件。

显然,我可以轻松修复此示例,但我想知道为什么没有引发异常。这个我见多了。

这是一个例子:

public DataTable GetTaskDescription( string EstmateNameGuid)
    {
        string strJobNumName = null;

        MySqlCommand cmd = null;
        MySqlDataReader dr = null;
        MySqlConnection myconnection = new MySqlConnection(clsGlobeVar.localDB);
        myconnection.Open();
        DataTable table1 = new DataTable("EstGuids");

        string select = GetTaskDescription_SQLCreate();
        try
        {

            cmd = new MySqlCommand(select, myconnection);
            GetTaskDescription_ParameterFill(ref  cmd, clsGlobeVar.ClientGuid, EstmateNameGuid);

            dr = cmd.ExecuteReader();

            if (dr.HasRows)
            {                 
                table1.Columns.Add("Estimate_Guid");
                table1.Columns.Add("Estimate_Description");
                table1.Columns.Add("Estimate_Date");
                table1.Columns.Add("Active");
                string [] field = new string[5] ;

                while (dr.Read())
                {  
                    // going to read field in the row.
                    field[0] =  dr.SafeGetString(0);
                    field[1] =  dr.SafeGetString(1);
                    field[2] =  dr.SafeGetString(2);
                    field[3] =  dr.SafeGetString(3);
                      // this field does not exist but I tried to read it
                     // this should fail and raise an exception  
                     // it does fail but does not raise the exception
                    field[4] =  dr.SafeGetString(4);
                }
    }

   // this catch is ignored
catch (MySqlException ex)  
     {  some code }

// the finally block executes okay
finally  { some clean up}
// and this return statement is ignored and the code in the caller does not execute
return table1
}

感谢您的帮助。

【问题讨论】:

  • 也许你没有抛出 mysqlexception,尝试捕获异端异常,看看抛出了什么错误
  • 你是对的。即使我只使用 mysql 对象,我也没有抛出 mysqlexception。在这里可以学到很多东西。谢谢。

标签: c# mysql exception datareader


【解决方案1】:

通常不建议以这种方式处理异常,因为您永远无法确定嵌套代码实际抛出了哪些异常。 您至少应该为意外事件添加一个处理程序:

catch (MySqlException ex)  
 {  some code }
catch (Exception ex)
{
   //Unexpected exception thrown...
}

【讨论】:

  • 做到了。我想一般来说我没有捕捉到正确的例外。 .更多学习....感谢您的帮助。
  • 有一篇关于异常处理的好文章您可能想阅读。它由 stackoverflow 的创始人之一 Joel Spolsky 撰写:joelonsoftware.com/items/2003/10/13.html
  • 乔尔显然不是粉丝。也不是这里的真正粉丝。我不喜欢的部分是未捕获的异常如何将您送到外太空,而您不知道自己是如何到达那里的。 4 函数/方法调用深度和出现问题并繁荣,你在画屏幕。 8(...不知道你是怎么到那里的。一个巨大的 goto。你如何避免它?
  • 我认为基本点是,您应该始终尽快捕获错误,然后在可能的情况下提供适当的处理。此处或那里的意外异常的备用 catch() 也应该在那里 - 只是不要依赖它们。
猜你喜欢
  • 2020-03-23
  • 2023-02-02
  • 1970-01-01
  • 1970-01-01
  • 2012-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-14
相关资源
最近更新 更多