gpt4 book ai didi

.net - VB.Net 用户定义异常的例子?

转载 作者:行者123 更新时间:2023-12-03 18:08:32 25 4
gpt4 key购买 nike

很简单地说,我想知道这里是否有人可以给我一个 VB.Net 中用户定义异常的示例。我已经有两个可以在网上找到的例子,但除此之外,我想不出更多了。我需要找到至少 5 个来做笔记,然后提交给我的老师。

到目前为止,我拥有的两个是:无效的登录信息(例如不正确的用户名或密码),以及在线商店中过期的信用卡信息。任何帮助将不胜感激。

最佳答案

基本要求是在项目中添加一个继承自内置类 System.Exception 的新类。 .这让您几乎可以免费获得所需的一切,因为它全部在 System.Exception 内部实现。类(class)。

唯一需要添加到类文件的是构造函数(因为请记住,构造函数不是继承的)。虽然您不必定义所有三个标准构造函数,但我强烈建议您这样做,以便您的接口(interface)与 .NET Framework 提供的所有异常类保持一致。定义一次并不难,recommended by code analysis tools .

最后(这是大多数人忘记的步骤,包括那些发布此问题其他答案的人),您需要使您的异常可序列化。通过添加 SerializableAttribute 来做到这一点到类声明并添加 Protected序列化机制内部使用的构造函数。该属性不是从 System.Exception 继承的。 ,并且必须明确说明。

既然你问得这么好,这里有一个完整的例子,上面所有的都实现了:

''' <summary>
''' The exception that is thrown when DWM composition fails or is not
''' supported on a particular platform.
''' </summary>
<Serializable()> _
Public Class DwmException : Inherits System.Exception

''' <summary>
''' Initializes a new instance of the <see cref="DwmException"/> class.
''' </summary>
Public Sub New()
MyBase.New()
End Sub

''' <summary>
''' Initializes a new instance of the <see cref="DwmException"/> class
''' with the specified error message.
''' </summary>
''' <param name="message">The message that describes the error.</param>
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub

''' <summary>
''' Initializes a new instance of the <see cref="DwmException"/> class
''' with the specified error message and a reference to the inner
''' exception that is the cause of this exception.
''' </summary>
''' <param name="message">The message that describes the error.</param>
''' <param name="innerException">The exception that is the cause of the
''' current exception, or a null reference if no inner exception is
''' specified</param>
Public Sub New(ByVal message As String, ByVal innerException As System.Exception)
MyBase.New(message, innerException)
End Sub

' Constructor required for serialization
<SecuritySafeCritical()> _
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
MyBase.New(info, context)
End Sub

End Class

啊,在发布上述内容后,我意识到我可能完全误解了你的问题。我(和其他答案)认为您是在询问如何实现用户定义的异常类的示例。看起来您只是在询问您何时会在自己的项目中做这样的事情的例子......这要棘手得多。

大多数时候,你 不要想要这样做。只有在编写可重用代码库(如 .DLL 文件)时才应该抛出自定义异常,并且您希望客户端代码根据所抛出的特定异常做出不同的 react 。所以,就我而言,我抛出一个 DwmException来自我的类​​库,因为当用户计算机上未启用 DWM 组合时,客户端应用程序可能想要捕获该异常并禁用一些精美的 UI 功能。通常,我会抛出一个标准 NotSupportedException ,但在这种情况下,我想为客户提供区分他们可以处理的异常和他们不能或不应该处理的异常的能力。

在标准应用程序中,所有代码都是独立的(即,当您不创建可重用的代码库时),您基本上不应该创建/抛出自定义异常。扔一个标准的,而不是。遵循上述规则,如果您需要引发自定义异常以影响客户端代码的 react 方式,这表明您在应用程序内部使用异常进行“流控制”(因为生产者和消费者是一个同样),强烈建议不要这样做。

关于.net - VB.Net 用户定义异常的例子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6086116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com