【发布时间】:2016-05-28 20:16:34
【问题描述】:
如何在我的代码中捕获多个异常?就像我对Delete 操作有以下代码一样,我想为REFERENCE constraint 和SqlConnection 异常捕获异常。
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");
}
}
有可能吗?
【问题讨论】:
标签: c# exception exception-handling