Chris's Event Programming with Visual Basic course.

Contents
Introduction

Conventions

Starting VB3

The development environment

Help Documentation

The "On-line" Tutorial

Starting a new project

Making an application

Working with Forms

Modal forms

Multiple Document Interface (MDI)

Building the interface

Menus 

Tool Bars & Control Arrays

Building a Control Array

Z Order

Custom controls

Handling Data

Input Boxes

Message Boxes

Error Trapping

The Data Manager

Data Aware Components

Debugging code

Compilation of code 


 
 
 
 

Error Trapping
Error trapping in code makes use of the OnError statement. If an expression is not used to trap errors then erroneous input can cause your application to fail unexpectedly. This could be seen with the code we have just written, If this is ran and non-numeric values are passed to the InputBox dialogue a fatal error occurs. Amend the code to read as below:

Sub Command1_Click ()
Dim answer, DefVal, Msg, Title, resp
    On Error GoTo Err1                                   'amended
    Msg = "Enter a value from 1 to 3 to continue, or 4"
    Title = "InputBox Demo"
    DefVal = "1"
    Do
        answer = InputBox(Msg, Title, DefVal)
    Loop Until answer >= 1 And answer <= 4
    If answer = 4 Then
        resp = MsgBox("Change Forms?", 52)
        If resp = 6 Then
            form2.Show
        End If
    Else
        MsgBox "You entered " & answer
    End If
    Exit Sub                                              'amended to skip below
Err1:                                                     'error handling routine
    MsgBox "Error is type " & Err                        'reports error number
    If Err = 13 Then                                     '13 is type mismatch
        answer = 999                                     'resets the answer to a safe incorrect value
    End If
    Resume     ‘allows processing to continue from the next statement
End Sub
 

If this is ran and an incorrect (alpha) character or string is input into the input box dialogue then the error is reported and processing continues. Note that the variable answer is given a safe value before Resume because it is evaluated in a loop. If the error occurs in that loop and it is not given a safe value, the Resume will cause an infinite loop to occur. Save the project as VB3aa5.mak, (where aa is your initials).
 
 
 

Visual Basic and all other Microsoft products mentioned in this series are trademarks of the Microsoft Corporation.