How to: Create New Exception Classes in Visual Basic

You can create your own application exception classes by inheriting them from the Exception class. Follow good coding practices by ending the class name of your exception with the word Exception, such as OutOfMoneyException or TooMuchRainException.

The following code example provides a basic implementation of an exception class.

Example

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic Language. For more information, see How to: Insert IntelliSense Code Snippets.

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

Compiling the Code

  • Replace YourProblemException with the name of the exception class you want to create. Typically, exception class names end with "Exception". Add properties to convey additional information about the error that has occurred.

Security

Do not divulge information about the application or its data when handling an exception. This information could be used to attack your application.

See Also

Tasks

Troubleshooting Exception Handling (Visual Basic)

Reference

ApplicationException

Concepts

Structured Exception Handling Overview for Visual Basic

Other Resources

Exception Handling Tasks (Visual Basic)