VB.Net用户定义的异常示例?

时间:2011-05-22 04:46:41

标签: .net vb.net exception exception-handling

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

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

2 个答案:

答案 0 :(得分:29)

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

您需要添加到类文件中的唯一内容是构造函数(因为,请记住,构造函数不是继承的)。虽然您不必定义所有三个标准构造函数,但我高度建议您这样做,只是为了使您的接口与.NET Framework提供的所有异常类一致。一次定义它们并不难,recommended by code analysis tools

最后(这是大多数人忘记的步骤,包括那些发布此问题的其他答案的人),您需要将您的异常序列化。通过将SerializableAttribute添加到类声明并添加由序列化机制在内部使用的Protected构造函数来实现。属性 not 继承自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文件),并且你希望客户端代码根据特定的方式对做出不同的反应被抛出的异常。因此,在我的情况下,我从类库中抛出DwmException,因为客户端应用程序可能希望捕获该异常并在用户计算机上未启用DWM组合时禁用某些奇特的UI功能。通常,我只会抛出一个标准NotSupportedException,但在这种情况下,我想让客户端能够区分他们可以处理的异常和他们不能处理的异常或者不应该。

在标准应用程序中,所有代码都是自包含的(即,当您创建可重用的代码库时),您基本上应该从不创建/抛出自定义异常。相反,扔一个标准的。遵循上述规则,如果您需要抛出一个自定义异常来影响客户端代码的反应,那么这表明您在应用程序内部使用了“流控制”的异常(因为生产者和消费者是一个在同一个),强烈气馁。

答案 1 :(得分:0)

相关问题