我得到的是從數據庫中,它看起來像或多或少這樣的填充數據集的方法:的WinForms異常處理
private DataSet GetData(string query)
{
try
{
//do some stuff to populate dataset
return dataset;
}
catch (SqlException ex)
{
MessageBox.Show("There was a database error. Please contact administrator.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
LogExceptionToFile(ex); //to log whole exception stack trace, etc.
}
finally
{
//cleanup
}
}
//calling methods:
GetData(query);
OtherMethod1(); //this method shows message box of success
當我有一段代碼在例外的情況下,我得到了我的用戶友好的消息框然後調用OtherMethod1()
並顯示成功消息框。如果在GetData()
有錯誤,我想停止。當我在消息框後添加throw;
到此catch塊時,顯示的另一個消息框比拋出未處理的異常。如果我提供了友好的信息,我想避免顯示第二個消息框。
如果您在'GetData()'方法中添加'throw',則需要圍繞該方法進行try/catch以實際捕獲異常。否則,您需要一些變量來跟蹤GetData中的成功/失敗,然後根據是否存在異常來採取相應措施。 –