【问题标题】:Catching Multiple Exceptions-C# [duplicate]捕获多个异常-C# [重复]
【发布时间】:2016-05-28 20:16:34
【问题描述】:

如何在我的代码中捕获多个异常?就像我对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)));
    }  
} 

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

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


    【解决方案1】:

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

    【讨论】:

    • 有效吗? catch (SqlConnection ex) 。我收到错误SqlConnection doesn't exist
    • 我想他可能是指SqlException
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    • 2020-05-10
    • 2011-01-31
    • 2012-07-13
    • 2011-12-07
    • 2012-09-22
    相关资源
    最近更新 更多