0

How can I catch multiple Exceptions in my code? Like I have the following code for Delete operation, I want to catch Exception for REFERENCE constraint and for SqlConnection Exception.

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

Then in my client code I want to check the type of Exception thrown so I can show a personalized message to the user:

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

Is it possible?

Huma Ali
  • 1,759
  • 7
  • 40
  • 66

1 Answers1

5

You can catch specific exception in separate catch blocks

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...
}  

As for good coding practice don't catch generic exception -catch (Exception ex) instead you catch only specific exception which you are expecting and dont catch generic exception. Even if you catch them throw them.

catch (Exception ex) 
{
  // do your logging only if required
   throw; //throw it back
}  
Carbine
  • 7,849
  • 4
  • 30
  • 54