捕获多个异常 - C#

Hum*_*Ali 0 c# exception-handling exception

如何在代码中捕获多个异常?就像我有以下代码进行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)));
    }  
} 
Run Code Online (Sandbox Code Playgroud)

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

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

可能吗?

Car*_*ine 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...
}  
Run Code Online (Sandbox Code Playgroud)

至于良好的编码实践,不要捕获泛型异常 - catch (Exception ex)而是只捕获您期望的特定异常,并且不捕获泛型异常.即使你抓住他们扔他们.

catch (Exception ex) 
{
  // do your logging only if required
   throw; //throw it back
}  
Run Code Online (Sandbox Code Playgroud)

  • 我想他可能意味着SqlException (2认同)