c# - 为什么要使用特定的异常捕获 block

标签 c# asp.net exception-handling

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

我的问题是,为什么我不能使用 Exception 类来捕获代码中的每一个可能的异常并获取堆栈跟踪?

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

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

最佳答案

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

提出相同问题的更好方法是“捕获不太具体的异常类型的缺点是什么”。这个问题的答案非常简单:您可能会无意中捕捉到您不知道如何处理的异常。

通常,代码应该只在知道如何处理异常时才捕获异常,例如报告错误,使用计数器重试,要求最终用户决定如何继续,等等。仅当您将捕获的异常限制为特定组时才有可能,例如 DbUpdateException

捕获特定异常的一个很好的“好处”是您可以访问仅在特定子类上定义的属性和方法。例如,DbUpdateException 告诉您哪些条目未能通过 Entries 保存属性,它让您有机会尝试重试。

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

关于c# - 为什么要使用特定的异常捕获 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47540695/

相关文章:

c# - C#文本框到列表框

c# - asp.net core 2.0身份 Entity Framework 用户未保存

c# - 在接口(interface)中创建通用属性

exception - Haskell 中的安全应用

c# - OOP - 使用改变实现的方法和半固态的对象的正确设计

c# - 从 windows 7 上的 windows 服务读取 HKLM

c# - 如何进行时间间隔的计算?

asp.net - 播放视频时服务器出错 : HTTP Error 404. 3

entity-framework - 在 Entity Framework4 中捕获 Sql 异常?最佳实践是什么?

c# - ASP.NET C# 捕获类中的所有异常