I am new to C# and I find some of the exception handling, or lack there of to be puzzling. I am trying to catch these exceptions but they are not caught I don't understand why. The code will cak after the exception and everything after the exception will be ignored, the next line executed will be a paint event for the form.
Obviously I can fix this example easily but I want to know why the exception is not raised. I have seen this quite a bit.
Here is an example:
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
}
Thanks for any help.
Handling exceptions in this way is generally not recommended, as you can never be sure what exceptions your nested code actually throws. You should at least add a handler for unexpected ones:
catch (MySqlException ex)
{ some code }
catch (Exception ex)
{
//Unexpected exception thrown...
}