2016-02-17 62 views
0

如何捕獲我的代碼中的多個異常?像我有Delete操作下面的代碼,我想趕上例外REFERENCE constraintSqlConnection例外。捕捉多個異常-C#

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

這可能嗎? catch (Exception ex),而不是你抓住你期待只有特定的例外,不追趕通用的異常 -

回答

4

您可以在單獨的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) 
{ 
    // do your logging only if required 
    throw; //throw it back 
} 
+0

它有效嗎? catch(SqlConnection ex)'。我得到錯誤'SqlConnection不存在' –

+2

我想他可能是指SqlException – MaxJ