捕获多个异常-C#
如何捕获代码中的多个异常?就像我有以下用于捕获多个异常-C#,c#,exception,exception-handling,C#,Exception,Exception Handling,如何捕获代码中的多个异常?就像我有以下用于Delete操作的代码一样,我希望捕获REFERENCE constraint和SqlConnection异常的异常 public void DeleteProduct(Product p) { try { using (IDbCommand cmd = dbConnection.CreateCommand()) { cmd.CommandType = CommandType.Sto
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");
}
}
可能吗?您可以在单独的捕获块中捕获特定异常
try
{
using (IDbCommand cmd = dbConnection.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = SpDeleteProduct;
dbConnection.Open();
cmd.ExecuteNonQuery();
}
}
catch (SqlException ex)
{
//Your exception specific code...
}
catch (Exception ex)
{
//Your exception specific code...
}
至于好的编码实践,不要捕获一般异常-catch(exception ex)
相反,您只捕获您期望的特定异常,而不捕获一般异常。即使你抓住了他们,也要扔掉他们
catch (Exception ex)
{
// do your logging only if required
throw; //throw it back
}
您可以在单独的catch块中捕获特定异常
try
{
using (IDbCommand cmd = dbConnection.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = SpDeleteProduct;
dbConnection.Open();
cmd.ExecuteNonQuery();
}
}
catch (SqlException ex)
{
//Your exception specific code...
}
catch (Exception ex)
{
//Your exception specific code...
}
至于好的编码实践,不要捕获一般异常-catch(exception ex)
相反,您只捕获您期望的特定异常,而不捕获一般异常。即使你抓住了他们,也要扔掉他们
catch (Exception ex)
{
// do your logging only if required
throw; //throw it back
}
它有效吗<代码>捕获(SqlConnection ex)。我得到错误
SqlConnection不存在
我想他可能是指sqlexception它有效吗<代码>捕获(SqlConnection ex)。我发现错误SqlConnection不存在
我想他可能是指SqlException