何时使用用户定义的异常和一些好的示例/最佳实践?
我假设大多数用户定义的异常都是针对业务逻辑级别的异常,但是使用用户定义的异常有哪些好的理由?有哪些好的示例?
用户定义的异常的唯一优点是可以定义一致的错误消息吗?
在异常中可以编写什么逻辑才能使它们真正更有用?
毕竟,你不能这样做:throw new Exception("Some Error Message");
I would assume that most User-defined Exceptions are for Business Logic level exceptions, but what are some good reasons to use a User-Defined Exception and what are some good examples?
Is a user-defined exception's only advantage that you can define a consistent Error Message?
What logic can be written inside exceptions to make them truly more useful?
After all, can't you just do this: throw new Exception("Some Error Message");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
用户定义的异常很有用,因为它允许您以特定的方式处理不同类型的错误。如果 .NET 可以使用不同的文本消息将所有异常作为 System.Exception 抛出,那么为什么它们要定义这么多不同类型的异常呢? .NET 中存在不同类型的异常的原因是您可以捕获各种类型的错误并以不同的方式处理它们。这与您定义自己的用户异常的原因相同 - 以便您可以根据发生的异常类型提供不同的响应。
您还可以创建包含附加数据的用户定义的异常。例如,您可以根据枚举、整数错误代码或任何其他可能对调用程序有用的内容来定义严重性级别,以识别出了什么问题。至于异常中包含的逻辑,我通常只是尝试报告出了什么问题,并将逻辑(如何处理错误)留给调用程序。在某些情况下,如果错误超过了特定的严重级别,我会让异常代码自动将错误写入日志文件(例如,抛出警告,但仅将严重错误写入日志文件)。
Having user-defined exceptions is useful because it allows you to handle different kinds of errors in specific ways. Why does .NET define so many different types of exceptions if they could just throw all exceptions as System.Exception with a different text message? The reason that there are different types of exceptions in .NET is that you can catch individual types of errors and handle them differently. That's the same reason you would define your own user exceptions - so that you can provide a different response based on the type of exception that occurred.
You can also create user-defined exceptions that include additional data. For example, you could define a severity level based on an enum, an integer error code or anything else that might be useful to the calling program to identify what went wrong. As for logic to include in exceptions, I generally just try to report what went wrong and leave the logic (what to do about the error) to the calling program. In some cases, I have the exception code automatically write the error to a log file if it has exceeded a certain severity level (e.g. warnings are thrown but only critical errors are written to the log file).
您应该创建很少的用户定义的异常。仅当有人要捕获异常并对其执行特定操作时才应使用它们。如果抛出异常而不是
InvalidOperationException
不会使代码的行为有所不同,则抛出InvalidOperationException
。You should create very few user-defined exceptions. They should only be used if someone is going to catch the exception and do something specific with it. If throwing your exception instead of
InvalidOperationException
is not going to make the code behave differently, then throwInvalidOperationException
..NET 框架中已有相当多的异常,如果您能找到可用于您的特殊情况的异常,则应该使用它们。
例如,在我的配置类(通常是
ConfigurationManager
周围的包装器)中,当无法正确解析值时,我会抛出ConfigurationErrorsException
。当从文本或其他需要特定格式的内容解析自定义值并且解析失败时,我会抛出
FormatException
但是,如果我的
BankAccount
对象中没有足够的钱如果我要提取 10 英镑,那么我会编写并抛出InsufficentFundsException
因为这样我就可以处理特定的错误情况(如果发生)。希望这(在某种程度上)有帮助。
There are quite a lot of Exceptions already in the .NET framework, which you should use if you can find one that could be used for your exceptional circumstance.
For example, in my configuration classes (which are normally wrappers around the
ConfigurationManager
) I throwConfigurationErrorsException
when ever a value can't be parsed correctly.When parsing custom values from text or something else that requires a specfic format and the parsing fails, I throw a
FormatException
However if my
BankAccount
object doesn't have enough money in it for me to withdraw £10 then I'll write and throwInsufficentFundsException
because then that way I can handle that specific error case, if it ever occurs.Hope this (somewhat) helps.
不,它们不仅仅用于消息。您可以在 catch 块的异常列表中查找用户定义的异常。
您可以随时使用用户定义的异常来查找发生的特定情况。也许客户端 ID 超出了指定范围,您需要专门查找该范围。您不必解析错误消息(这可能很痛苦,并且容易出错,例如消息稍后发生更改),您可以使用一个异常,并且您知道代码中的其他地方专门告诉您你“嘿,这件事发生了。你需要意识到这一点。”
No, they are not only for messages. You can look for User defined ones in the exception list of a catch block.
You can use User Defined Exceptions anytime you want to look for something specific that occurs. Maybe a Client ID is out of a specified range and you want to look for that specifically. Instead of having to parse the error message (which can be a pain, and is prone to errors, like if the message changes later down the road), you have an exception you use and you know that somewhere else in the code is specifically telling you "Hey this happened. You need to be aware of it."
用户定义的异常可以在组件中使用,以允许组件的使用者能够以比 catch (Exception) 块更大的粒度来捕获它们。这将为组件使用者提供执行不同任务的能力,基于抛出的异常。仅当真正期望消费者使用它们以这种方式进行区分时,才应真正创建用户定义的异常。
User defined exceptions can be used within a component to allow consumers of the component the ability to catch them with a greater level of granularity then the catch (Exception) block. This will provide the component consumer with the ability to perform different tasks, based on which exception has been thrown. User defined exceptions should only really be created when there is a real expectation that consumers will use them to differentiate in this way.
您还可以添加属性来存储具有用户定义异常的其他元数据,例如错误代码(例如调用非托管 API 时)。这比简单地将内容放入 Exception 对象的 Data 属性中更加用户友好。
You can also add properties to store additional meta-data with a user-defined exception, such as an error code (for example when calling an unmanaged API). This is more user-friendly than simply putting stuff into the Data property of the Exception object.