捕获多个异常 - C#

时间:2016-02-17 08:27:25

标签: c# exception exception-handling

如何在代码中捕获多个异常?就像我有Delete操作的以下代码一样,我希望捕获REFERENCE constraintSqlConnection例外的异常。

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)));
    }  
} 

然后在我的客户端代码中,我想检查抛出的Exception类型,以便向用户显示个性化消息:

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");
    }
}

有可能吗?

1 个答案:

答案 0 :(得分:5)

您可以在单独的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
}