c# - 异常处理 : user defined exception benefits

标签 c# c#-4.0 programming-languages exception-handling

我的异常处理技能非常初级,我总是很困惑我应该如何使用它们,而不是如何/语法。我目前正在使用 C#(如果有不同的东西适用的话)。

我的问题是,在开发应用程序时创建自己的异常类有什么好处?与抛出标准 Exception 类异常相比。基本上什么是您的应用程序中异常的健康实践。

或者如果没有好处,那就是缺点?

最佳答案

通过创建您自己的异常,您通常可以为最终用户创建更有意义的消息(或更特定于应用程序的消息类型),同时仍然包装原始消息,以免丢失任何有用的信息。

有一个很棒的 book by Bill Wagner 涵盖了一些关于何时应该或不应该创建自己的异常的推理,以及一些一般异常处理的良好实践。这是一小段摘录:

Your application will throw exceptions -- hopefully not often, but it will happen. If you don't do anything specifc, your application will generate the default .NET Framework exceptions whenever something goes wrong in the methods you call on the core framework. Providing more detailed information will go a long way to enabling you and your users to diagnose and possibly correct errors in the field. You create different exception classes when different corrective actions are possible and only when different actions are possible. You create full-featured exception classes by providing all the constructors that the base exception class supports. You use the InnerException property to carry along all the error information generated by lower-level error conditions.

关于c# - 异常处理 : user defined exception benefits,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6709518/

相关文章:

c# - 如何在不粘贴的情况下从内存中获取复制的文本?

c# - 如何在 blazor 项目中使用 C# 绑定(bind)制作 HTML 文本多行?

c# - 从集合中删除重复项,但第一次出现除外

c# - 在 .NET 4 中使用 IntPtr 时出现 PInvokeStackImbalance 异常? (适用于 .NET 3.5)

haskell - 我们关心 FRP 中的 'past' 吗?

Perl 闭包和 $_

c# - 在另一个 ContentControl 之后插入一个 ContentControl

optimization - 通过 XLS 操作提高性能

c# - 根据其他属性设置属性的方式

regex - 所有正则表达式实现的列表?