捕获多个异常 - C#

本文关键字:异常 | 更新日期: 2023-09-27 18:35:03

如何在代码中捕获多个异常?就像我有以下用于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#

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