如何:在 Visual Basic 中创建新的异常类

通过继承 Exception 类可以创建自己的应用程序异常类。 遵循良好的编码规范,异常的类名称以单词 Exception 结尾,如 OutOfMoneyException 或 TooMuchRainException。

下面的代码示例提供了异常类的基本实现。

示例

此代码示例也可用作 IntelliSense 代码段。 在代码段选择器中,它位于**“Visual Basic 语言”**中。 有关更多信息,请参见如何:插入 IntelliSense 代码段

Public Class YourProblemException
    Inherits Exception

    Public Sub New()
        ' Add other code for custom properties here.
    End Sub

    Public Sub New(ByVal message As String)
        MyBase.New(message)
        ' Add other code for custom properties here.
    End Sub

    Public Sub New(ByVal message As String, ByVal inner As Exception)
        MyBase.New(message, inner)
        ' Add other code for custom properties here.
    End Sub

    Public Sub New(
        ByVal info As System.Runtime.Serialization.SerializationInfo,
        ByVal context As System.Runtime.Serialization.StreamingContext)
        MyBase.New(info, context)
        ' Insert code here for custom properties here.
    End Sub
End Class

编译代码

  • 用要创建的异常类的名称替换 YourProblemException。 通常,异常类名称以“Exception”结尾。 添加属性以传递有关发生的错误的更多信息。

安全性

处理异常时,不要泄露有关应用程序或其数据的信息。 这些信息可用来攻击您的应用程序。

请参见

任务

异常处理疑难解答 (Visual Basic)

参考

ApplicationException

概念

Visual Basic 的结构化异常处理概述

其他资源

异常处理任务 (Visual Basic)