0
如何捕獲我的代碼中的多個異常?像我有Delete
操作下面的代碼,我想趕上例外REFERENCE constraint
和SqlConnection
例外。捕捉多個異常-C#
public void DeleteProduct(Product p)
{
try
{
using (IDbCommand cmd = dbConnection.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = SpDeleteProduct;
dbConnection.Open();
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
throw new FaultException(new FaultReason(new FaultReasonText(ex.Message)));
}
}
然後在我的客戶端代碼我想檢查拋出的異常的類型,所以我可以顯示個性化的信息給用戶:
void DeleteProductCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
FaultException fault = e.Error as FaultException;
//Something like
// if e.Error == SqlConnection Exception
GetExceptionMessage("Error occured in connecting to DB");
// if e.Error == Refeence constraint Exception
GetExceptionMessage("foreign key violation");
}
}
這可能嗎? catch (Exception ex)
,而不是你抓住你期待只有特定的例外,不追趕通用的異常 -
它有效嗎? catch(SqlConnection ex)'。我得到錯誤'SqlConnection不存在' –
我想他可能是指SqlException – MaxJ