Why use specific exception catch blocks

Viewed 1394

In the code below, I have a catch block for System.Data.Entity.Infrastructure.DbUpdateException class exception.

My question is that why I can't use Exception class to catch each and every possible exception in my code and get stacktrace?

What is the advantage of specific exception types and their use in multiple catch blocks?

try
{
    AddAdminUserInput input1 = JsonConvert.DeserializeObject<AddAdminUserInput>(input);
    Foundation_Services_DL_DataEntities Db = DLMetadataContext.GetContext();
    UserAccount account = new UserAccount
    {
        emplid = input1.emplid,
        sso = input1.sso,
        deptid = input1.deptid,
        usertype = input1.usertype,
        status = input1.status,
        username = input1.username
    };

    Db.UserAccounts.Add(account);
    Db.SaveChanges();

    Dictionary<string, string> dict = new Dictionary<string, string>();
    dict.Add("status", "0");
    dict.Add("message", "User Addition Successful");

    Context.Response.Write(JsonConvert.SerializeObject(dict));
}
catch (System.Data.Entity.Infrastructure.DbUpdateException dbev)
{
    Dictionary<string, string> dict = new Dictionary<string, string>();
    dict.Add("status", "1");
    dict.Add("message", "User Addition Failed - User Already Exists");

    Context.Response.Write(JsonConvert.SerializeObject(dict));
}
3 Answers
Related