Try/Catch does not catch

自闭症网瘾萝莉.ら 提交于 2019-12-10 21:23:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!