April 22, 2019
Hot Topics:

Custom Exceptions in VB 2005

  • March 13, 2006
  • By Josh Fitzgerald
  • Send Email »
  • More Articles »

Custom Exception: CustomerNotFoundException

The first custom exception class is called CustomerNotFoundException. You will throw this exception when you attempt to look up a customer in your database but do not find a match. The code is listed below:

Public Class CustomerNotFoundException
   Inherits DatabaseException
   Private m_CustomerID As Long
   Public ReadOnly Property CustomerID() As Long
         Return m_CustomerID
      End Get
   End Property
   Public Sub New(ByVal customerID As Long)
      MyBase.New("Customer ID was not found.")
      m_CustomerID = customerID
   End Sub
End Class

This class inherits from the DatabaseException base class you created earlier. It contains only one constructor, which takes the customerID as a parameter. When this constructor is called, you pass the text string "Customer ID was not found." into the constructor of the base class to be used as the Message property. You also have a readonly property called CustomerID defined. You will use the CustomerID property to store the value of the customer ID that was passed in as a parameter. It is a readonly property because it does not make any sense to change the value to something other than the value that caused the exception.

Custom Exception: DatabaseUnavailableException

The second custom exception class is called DatabaseUnavailableException. You will throw this exception when an exception occurs while you're attempting to connect to the database. The code is listed below:

Public Class DatabaseUnavailableException
   Inherits DatabaseException
   Public Sub New(ByVal ex As Exception)
      MyBase.New("The database is not available.", ex)
   End Sub
End Class

This class is very similar to your CustomerNotFoundException class. You do not have any additional properties defined for this class, but the primary difference is that it takes a System.Exception as a parameter and passes it into the constructor in your base class. This System.Exception parameter will become the InnerException property of your DatabaseUnavailableException.

Customer Class

The Customer class is a simple class that takes a database name and a customer ID as parameters for the constructor and attempts to retrieve the data for that customer. The first thing the constructor does is attempt to connect to the database by using the ConnectDB method as follows:

Private Sub ConnectDB(ByVal database As String, _
                      ByRef cn As OleDbConnection)
   cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; _
                          Data Source=" & _
                          """" & database & """"
   Catch ex As Exception
      Throw New DatabaseUnavailableException(ex)
   End Try
End Sub

You attempt to open the database connection inside a Try statement. If any exception is thrown, you catch it and throw a DatabaseUnavailableException, wrapping the original exception in its InnerException property.

If you make a successful connection to the database, you then try to retrieve the data for the specified customer ID using the GetCustomer method as follows:

Private Sub GetCustomerData(ByVal cn As OleDbConnection, _
                            ByVal customerID As Long)
   Dim cmd As New OleDbCommand
   Dim reader As OleDbDataReader
   cmd.Connection = cn
   cmd.CommandText = "SELECT * FROM CUSTOMER WHERE ID = " _
                     & customerID
   reader = cmd.ExecuteReader
   If reader.HasRows Then
      m_id = reader.Item("ID")
      m_firstname = reader.Item("Firstname")
      m_lastName  = reader.Item("Lastname")
      m_street    = reader.Item("Street")
      m_city      = reader.Item("City")
      m_state     = reader.Item("State")
      m_zipCode   = reader.Item("Zip")
      Throw New CustomerNotFoundException(customerID)
   End If
End Sub

You execute a SQL query using the customerID to specify which customer's data you want to retrieve. If the query returns a result, you set the properties of the Customer class using the values returned by the query. But, if you do not get any data, you throw a CustomerNotFoundException using the customerID as a parameter for the constructor. This value will be used to set the CustomerID property of your CustomerNotFoundException object.

App in Action

The following screenshots show your application in action. To run the application, call it from a command prompt and specify a database name and customer ID as arguments. The three screen shots show a successful query (see Figure 1), a CustomerNotFoundException being thrown (see Figure 2), and a DatabaseNotAvailableException being thrown (see Figure 3).

Figure 1. Successful Query

Figure 2. CustomerNotFoundException

Figure 3. DatabaseUnavailableException

Wrapping It Up

Custom exception types are a powerful feature of the VB .NET language. The .NET Framework provides many standard exception types that will suffice for most needs. In fact, you may rarely use anything but the standard exceptions, but the ability to create custom exceptions is a powerful tool to have.

Download the Code

To download the accompanying source code for the example, click here.

About the Author

Josh Fitzgerald is an applications development group leader for a large medical device company in Warsaw, Indiana. Designing and developing Visual Basic .NET applications is only one of his responsibilities, but it is his favorite part of his job. You can reach Josh at josh.fitzgerald@gmail.com.

Page 2 of 2

Comment and Contribute


(Maximum characters: 1200). You have characters left.



Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date