What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleUse standard and custom exception classes in Visual Basic .NET
DescriptionThis example shows how to use standard and custom exception classes in Visual Basic .NET.
Keywordsexception, exception classes, standard exceptions, custom exceptions, throw, throw exceptions, VB.NET, Visual Basic .NET
CategoriesSoftware Engineering
When your code encounters an error, it can throw an exception to tell the calling code what happened as in the following code:
' Return number!
Private Function Factorial(ByVal number As Long) As Long
    If (number < 0) Then
        Throw New ArgumentOutOfRangeException( _
            "number", "Factorial parameter must be at least " & _
    End If

    Dim result As Long = 1
    For i As Integer = 1 To number
        result *= i
    Next i

    Return result
End Function
The calling code can catch the error as in:
    txtNFactorial.Text = _
Catch ex As Exception
    MessageBox.Show("Error calculating factorial." _
        & vbCrLf & vbCrLf & ex.Message)
End Try
Throwing an exception is easiest if you can find an existing exception class that correctly represents your situation. The following list shows the hierarchy including some of the more useful exception classes.

Use the most specific class possible. If one of these classes isn't a good fit, derive your own class from the System.Exception class as in the following code.
Imports System.Runtime.Serialization

<Serializable()> _
Public Class InvalidAlgorithmException
    Inherits Exception

    Public Sub New()
    End Sub
    Public Sub New(ByVal message As String)
    End Sub
    Public Sub New(ByVal message As String, ByVal _
        inner_exception As Exception)
        MyBase.New(message, inner_exception)
    End Sub
    Public Sub New(ByVal info As SerializationInfo, context _
        as StreamingContext)
        MyBase.New(info, context)
    End Sub
End Class

  • If a standard exception doesn't closely resemble what you need, build your own exception class. Don't try to force a class to do something for which it was not intended or you'll make the code confusing. By convention, exception class names should end with Exception.
  • You don't need to catch every possible error and then throw a new exception. For example, if you simply try to parse an integer and the user has entered an invalid value, then Integer.Parse will throw an exception for you.
  • That being said, you may still want to catch this exception anyway and re-throw it with more specific information. For example, the new exception might tell the user which value had an invalid format or that the value must be an integer.
  • Use exceptions only for errors not return values or status conditions. Use parameters or method return values to give the calling code status information.
  • Don't use exceptions to catch unexpected but allowable values. For example, most orders might have no more than 20 items but it is possible that one might hahve 21. In that case, don't use an exception because that will prevent the program from handling unusual but possible situations. Instead use Debug.Assert to catch this suspicious condition in a debug build but to continue running in a release build.
  • Microsoft recommends that you not throw Exception, SystemException, NullReferenceException, or IndexOutOfRangeException from your code. I agree with the first two because they are too generic. Instead, derive your own more specific exception classes. (I'm not sure what Microsoft has against the last two.)

The example program demonstrates a couple kinds of exceptions. Enter -1 and click Factorial to make the program throw an ArgumentOutOfRangeException. Enter a non-numeric value and click Factorial to make the program allow Long.Parse to throw an error. Fionally click Throw Custom Exception to make the program throw a custom InvalidAlgorithmException.
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.