Megosztás a következőn keresztül:


Walkthrough: Structured Exception Handling

While you can still employ the On Error statement to handle exceptions in your code in order to provide unstructured exception handling, Visual Basic 2005 also supports structured exception handling, which you can use 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 demonstrates how to add structured exception handling to a program. Specifically, it shows 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.

Note

The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Visual Studio Settings.

Creating the Application

The following application is a customer order form for a company that sells teddy bears. The user interface consists of the following controls:

  • One TextBox for the customer's name.

  • Two ComboBox controls to select the color and size of the bear.

  • One Order Button.

  • Three labels that convey the purpose of each control to the user.

  • 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 Project. The New Project dialog box appears.

  2. In the Project Types window, select Visual Basic and Windows if these are not already selected, select Windows Application from the Templates window.

  3. In the Properties window under Name, enter TeddyBearProject and click OK. The project is added to the Solution Explorer, and the Windows Forms Designer opens.

  4. Add the controls 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

    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 them function. 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.

    Dim bearOrder As String
    bearOrder = _
      String.Format("You have ordered a {0} {1} bear.", _
      bearSize.SelectedItem, bearColor.SelectedItem)
    MsgBox(bearOrder)
    

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. Remember the following:

  • 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 expression type 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. In adding Try statements, be aware that the editor automatically supplies End Try at the end of the statement.

    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. Add 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 selected 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

Concepts

Structured Exception Handling Overview for Visual Basic

Reference

On Error Statement (Visual Basic)

Try...Catch...Finally Statement (Visual Basic)

Throw Statement (Visual Basic)

Other Resources

Exception Handling Tasks