捕获多个异常-c#

Catching Multiple Exceptions-C#

本问题已经有最佳答案,请猛点这里访问。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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)));
    }  
}

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

1
2
3
4
5
6
7
8
9
10
11
12
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");
    }
}

有可能吗?


您可以在单独的catch块中捕获特定的异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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),而是只捕获预期的特定异常,而不要捕获一般异常。即使你抓住他们,也要把他们扔出去。

1
2
3
4
5
catch (Exception ex)
{
  // do your logging only if required
   throw; //throw it back
}