问题
In following code I purposefully mistype "@fooData" to "@foo111Data" to check if the try statement is catching my exception. See below code. But the try/catch statement did not catch and display and exception in MessageBox, and VS2010 just break down and highlight the line of wrong code.
try
{
conn.Open();
cmd.Parameters.AddWithValue("@foo111Data", dataStrTb1.Text);
cmd.ExecuteNonQuery();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conn.Close();
}
回答1:
Perhaps an exception of a different type is being thrown? I would suggest that you change the catch
so that it just catches a general Exception
, and see if it's throwing another type.
Put a breakpoint in the catch
statement, on the MessageBox.Show
line, and then you can examine the Exception
.
回答2:
Try catching a SqlException
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
回答3:
instead of SqlCeException try to catch all Exceptions and see how it works.
I would actually use a logger and not simply the messagebox like you are doing now.
回答4:
Try
try
{
conn.Open();
cmd.Parameters.AddWithValue("@foo111Data", `dataStrTb1.Text);
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conn.Close();
}`
回答5:
There is a feature in Visual Studio which enables you to stop if an exception is thrown, even if it gets catched.
Simply click on the menuitem Debugging, then on Exceptions, then on column "thrown" and unmark certain exceptions you do not want to cause the debugger automatically to break.
来源:https://stackoverflow.com/questions/6199513/try-catch-does-not-catch