Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

4.13. Throw a Custom Exception

Problem

You need to indicate an application-specific error condition to the caller of your code.

Solution

Derive a custom exception object from the System.ApplicationException class, and add the recommended constructors. Use the Throw statement to throw the exception.

Discussion

.NET Framework guidelines suggest that you always use exception objects to indicate error conditions (not return values or another mechanism). If you need to indicate a generic error condition, use one of the existing framework exceptions (such as InvalidCastException, SecurityException, DivideByZeroException, or ArgumentException) with a custom description. If, however, you need to indicate an application-specific error, you should create a custom exception object. This custom exception object should derive from ApplicationException, not the base Exception class, and end with the word Exception.

Every exception should have the three basic constructors shown here:

Public Sub New()
    ' (Creates an uninitialized exception.)
    MyBase.New()
End Sub

Public Sub New(ByVal message As String)
    ' Creates an exception with a text message.
    MyBase.New(message)
End Sub

Public Sub New(ByVal message As String, ByVal inner As Exception)
    ' Creates an exception with a text message and a nested (inner)
    ' exception object.
    MyBase.New(message, inner)
End Sub

Notice that these constructors simply call the base class implementation, which performs the work.

In addition, you need to add a deserialization constructor to the Exception object if you want to make it serializable, along with the Serializable attribute.

The Serializable attribute is not enough on its own because the base Exception class implements ISerializable to perform custom serialization. If your exception does not include any data, this constructor can simply call the base class implementation:

Public Sub New(ByVal info As SerializationInfo, _
  ByVal context As StreamingContext)
    MyBase.New(info, context)
End Sub

Life becomes slightly more complicated if your exception adds its own properties. In this case, you must implement additional constructors to accept information for these properties. You must also implement GetObjectData to store the new information on serialization and configure the deserialization constructor so that it reads the new information. As an example, consider the custom exception shown here.

<Serializable()> _
Public Class CustomException
    Inherits ApplicationException

    ' The custom data.
    Private _CustomValue As Integer

    Public ReadOnly Property CustomValue() As Integer
        Get
            Return _CustomValue
        End Get
    End Property

    Public Sub New()
        MyBase.New()
    End Sub

    Public Sub New(ByVal message As String)
        MyBase.New(message)
    End Sub

    Public Sub New(ByVal message As String, ByVal inner As Exception)
        MyBase.New(message, inner)
    End Sub

    ' This constructor takes the added value.
    Public Sub New(ByVal message As String, ByVal value As Integer)
        MyBase.New(message)
        Me._CustomValue = value
    End Sub

    ' Store data during serialization.
    Public Overrides Sub GetObjectData(ByVal info As SerializationInfo, _
      ByVal context As StreamingContext)
        MyBase.GetObjectData(info, context) 
        info.AddValue("Value", Me._CustomValue)
    End Sub

    ' Retrieve data during deserialization.
    Public Sub New(ByVal info As SerializationInfo, _
      ByVal context As StreamingContext)
        MyBase.New(info, context)
        Me._CustomValue = info.GetInt32("Value")
    End Sub

End Class

					  

You can also override the Message property to give a better textual representation of your exception by incorporating the custom data with the message.

As with any other type of exception, you can throw the custom exception using the Throw keyword:

Throw New CustomException("Error", 100)