为什么使用特定的异常catch块

BIL*_*MAD 6 c# asp.net exception-handling

在下面的代码中,我有一个System.Data.Entity.Infrastructure.DbUpdateException类异常的catch块.

我的问题是为什么我不能使用Exception类来捕获我的代码中的每个可能的异常并获得stacktrace?

特定异常类型的优点是什么,以及它们在多个catch块中的使用?

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));
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 8

特定异常类型的优点是什么,以及它们在多个catch块中的使用?

提出相同问题的更好方法是"捕获不太具体的异常类型有什么缺点." 这个问题的答案非常简单:你可能会无意中发现一个你不知道如何处理的异常.

通常,代码只有在知道如何处理异常时才会捕获异常,例如报告错误,使用计数器重试,请求最终用户决定如何继续,等等.仅当您将捕获的异常限制为特定组时才可以执行此操作,例如DbUpdateException.

捕获特定异常的一个很好的"奖励"是,您可以访问仅在特定子类上定义的属性和方法.例如,DbUpdateException告诉您哪些条目无法通过Entries属性保存,这使您有机会尝试重试.

最后,某些例外意味着只能在您的程序的顶层捕获.这些异常表示编程错误 - 例如,访问null引用,访问结束后的数组或负索引,除以零等等.您的程序无法从这些错误中恢复,因为修复它们需要更改代码.因此,程序唯一能做的就是在退出或启动重启序列之前记录或以其他方式报告异常.