Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

Walkthrough: Structured Exception Handling

While you can still employ the On Error statement to handle exceptions in your code, Visual Basic .NET also supports structured exception handling, which enables you to create and maintain programs with comprehensive error handling. In structured exception handling, blocks of code test for specific circumstances and react accordingly.

This walkthrough uses the creation of a simple application to demonstrate how to add structured exception handling to a program. It explains how to use the Try...Catch...Finally statement to handle exceptions, and how to perform error filtering within Catch blocks.

Note   You cannot combine both structured and unstructured exception handling within a single procedure.

Creating the Application

The application in this walkthrough is a customer order form for a company that sells teddy bears. The user interface consists of the following controls: a TextBox for the customer's name, two ComboBox controls to select the color and size of the bear, and an Order button. When the user enters the requested information and clicks the Order button, the application displays a summary of the order.

To create the application

  1. From the File menu, select New, and then select Project. The New Project dialog box appears.
  2. In the Project Types window, select Visual Basic Projects if it is not already selected, and then choose Windows Application from the Templates window.
  3. In the Name box, set the project name to TeddyBearProject. The project is added to Solution Explorer, and the Windows Forms Designer opens.
  4. Add the controls in the following table to the form, and set their properties as specified.
    Control Properties Property Values
    Label Name
    Text
    customerLabel
    Bear Order Form
    TextBox Name
    Text
    customerName
    Customer Name
    Label Name
    Text
    bearColorLabel
    Available Colors
    ComboBox Name
    Items
    Text
    BearColor
    Black, Brown, Spotted
    Bear Color
    Label Name
    Text
    bearSizeLabel
    Available Sizes
    ComboBox Name
    Items
    Text
    BearSize
    Small, Normal, Large
    Bear Size
    Button Name
    Text
    Order
    Order

Adding Functionality

Now that the controls and their properties are added and set, you must place code behind them to make the application functional. The following code handles the Click event for the Order button and displays a message to the customer.

To add functionality to the form and its controls

  • Add the following code to the Order button's Click event:
    Private Sub order_Click(ByVal sender As System.Object, _
       ByVal e As System.EventArgs) Handles Order.Click
       Dim bearOrder As String
       bearOrder = _
         String.Format("You have ordered a {0} {1} bear.", _
         bearSize.SelectedItem, bearColor.SelectedItem)
       MessageBox.Show(bearOrder)
    End Sub
    

The application is now ready for you to add structured exception handling code.

Adding a Try...Catch Block

To ensure that the customer has specified a color for the bear, add a Try...Catch statement. Keep the following considerations in mind:

  • A Catch clause with no identifier catches all exceptions.
  • A Catch clause with a When clause catches exceptions only when the expression evaluates to True; the type of the expression must be implicitly convertible to Boolean.

To add a simple Try...Catch block

  • Add the following code to the Order button's Click event after the section that tests the size and color values, that is, after String.Format(("You have ordered a {0} {1} bear.", BearSize.SelectedItem, BearColor.SelectedItem). This code throws an exception if it encounters an invalid color value.
    Try
       If ((BearColor.SelectedIndex < 0) or _
             (BearColor.SelectedIndex > 2)) Then
          Throw New System.Exception()
       End If
    ' The Catch statement handles errors caused by a lack of bear color.
    Catch ex As Exception When BearColor.SelectedIndex < 0
       bearOrder = String.Format("You must select a bear color!")
    Finally
       Beep () ' Beep at the end.
    End Try
    

To add an additional Catch clause

  1. Add a new item, "Purple", to the BearColor ComboBox control.
  2. 8Add the following code after the code line bearOrder = String.Format("You must select a bear color!"):
    Catch ex As Exception When BearColor.SelectedIndex = 3
       bearOrder = String.Format("There are no bears of that color.")
    

You can add as many Catch clauses as necessary to your code.

Testing

You can now test the application to make sure it works correctly.

To build and run the application

  1. From the Build menu, select Build TeddyBearProject.
  2. Press F5 to run the application. The main form appears.

To test the application

  1. Enter a name in the Customer name text box, and then select a color and size for the bear from the Available Colors and Available Sizes combo boxes.
  2. Click the Order button. If you specified either Black, Brown, or Spotted as the color in the previous step, a message appears stating the size and color of the bear you ordered.

    If you do not specify a color, a message appears prompting you to do so.

  3. Click OK to cancel the message.
  4. In the Available Colors text box, select Purple, and then click the Order button. A message appears stating that purple bears are not available.

See Also

On Error Statement | Try...Catch...Finally Statements | Structured Exception Handling | Throw Statement | Throwing Exceptions from Components

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft