开发者

Try/Catch does not catch

开发者 https://www.devze.com 2023-03-09 22:15 出处:网络
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 a

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(开发者_Python百科);
}


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.


Try catching a SqlException

catch (SqlException ex)
{
    MessageBox.Show(ex.ToString());
}


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.


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(); 
}` 


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消