我是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
}
感谢您的帮助。
答案 0 :(得分:0)
通常不建议以这种方式处理异常,因为您永远无法确定嵌套代码实际抛出的异常。 您至少应该为意外的处理程序添加处理程序:
catch (MySqlException ex)
{ some code }
catch (Exception ex)
{
//Unexpected exception thrown...
}