You are on page 1of 22

VISUAL BASIC

PROGRAMMING DEC
5062
CHAPTER 4: DEBUGGING AND ERROR TRAPPING

[DATE]
[COMPANY NAME]
[Company address]
4.0 DEBUGGING AND ERROR TRAPPING
4.1. Know the Types of Error, Debugging and Error Trapping.
4.1.1. List the types of error.

What is Error?
Error can be defined as an act, assertion, or belief that unintentionally
deviates from what is correct, right or true.

In programming, the error may lead to a program not to run at all or run in
unintended behaviour.

There are three types of error:

i. syntax error

Occurs when the rule of VB syntax are violated. Example of syntax error is
using the reserved keyword as variable name:

Dim Sub as Integer

Then, forget to write End If in writing If Statement program:

If (mark>=90)
Txtmarkh.Text= You are excellent

return 0;

ii. logical error

It occurs when the program does not behave as intended, due to poor logic
or incorrect implementation

iii. runtime error


An error that occurs during the execution of a program. Runtime errors
indicate bugs in the program or problems that the designers had anticipated
but could do nothing about. For example, running out of memory will often
cause a runtime error.

4.1.2. Define the debugging.


Debugging is the routine process of locating and removing computer
program bugs, errors or abnormalities, which is methodically handled by
software programmers via debugging tools. Debugging checks, detects
and corrects errors or bugs to allow proper program operation according to
set specifications.

4.1.3. List the statement used in error trapping.


4.2. Understand the types of error, debugging and trapping process.
4.2.1. Describe the types of error.
4.2.2. Describe the debugging and error trapping process.

In Visual Basic, errors (also called exceptions) fall into one of three
categories: syntax errors, run-time errors, and logic errors.

Syntax Errors

Syntax errors are those that appear while you write code. Visual Basic checks
your code as you type it in the Code Editor window and alerts you if you
make a mistake, such as misspelling a word or using a language element
improperly. Syntax errors are the most common type of errors. You can fix
them easily in the coding environment as soon as they occur.

Run-time errors

Run-time errors are those that appear only after you compile and run your
code. These involve code that may appear to be correct in that it has no
syntax errors, but that will not execute. For example, you might correctly
write a line of code to open a file. But if the file is corrupted, the application
cannot carry out the Open function, and it stops running. You can fix most
run-time errors by rewriting the faulty code, and then recompiling and
rerunning it.

Logic Errors

Logic errors are those that appear once the application is in use. They are
most often unwanted or unexpected results in response to user actions. For
example, a mistyped key or other outside influence might cause your
application to stop working within expected parameters, or altogether. Logic
errors are generally the hardest type to fix, since it is not always clear where
they originate.

No matter how carefully crafted your code, errors can (and probably will)
occur. Ideally, Visual Basic procedures wouldn't need error-handling code at
all. Unfortunately, sometimes files are mistakenly deleted, disk drives run out
of space, or network drives disconnect unexpectedly. Such possibilities can
cause run-time errors in your code. To handle these errors, you need to add
error-handling code to your procedures.
Sometimes errors can also occur within your code; this type of error is
commonly referred to as a bug. Minor bugs for example, a cursor that
doesn't behave as expected can be frustrating or inconvenient. More
severe bugs can cause an application to stop responding to commands,
possibly requiring the user to restart the application, losing whatever work
hasn't been saved.
The process of locating and fixing bugs in your application is known
as debugging. Visual Basic provides several tools to help analyze how your
application operates. These debugging tools are particularly useful in
locating the source of bugs, but you can also use the tools to experiment
with changes to your application or to learn how other applications work.
This chapter shows how to use the debugging tools included in Visual Basic
and explains how to handle run-time errors errors that occur while your
code is running and that result from attempts to complete an invalid
operation.

ERROR TRAPPING

The On Error statement is used to trap errors in Visual Basic 6.


The On Error command must be placed in the procedure at a position
before the error could arise. The "Exit Sub" statement is used before the
error handling part in order to avoid running the error handling code when
there is no error. The Error object is built-in with global scope and contains
the state of errors that may have occurred.The Number property provides
the error number, and the Description property is a translation of the
error.

Private Sub drvList_Change()


On Error GoTo driveError
dirList.Path = drvList.Drive
Exit Sub
driveError:
MsgBox Err.Description, vbExclamation, "Drive
Error"
End Sub
THE RESUME STATEMENT

The Resume statement is used to specify where to restart the flow of


execution. This can either be a label, or Next. If Next is used, execution is
continued from the statement following the statement that caused the error.

The following example prompts the user what to do should a drive error
occur using the, Resume Next statement.
Private Sub drvList_Change()
On Error GoTo driveError
retryDrive:
dirList.Path = drvList.Drive
Exit Sub
driveError:
Dim response As Integer, description As Integer
description = vbExclamation + vbRetryCancel
response = MsgBox(Err.Description, description, "Drive
Error")
If response = vbRetry Then
Resume retryDrive
End If
End Sub
On Error Resume Next, skips any run-time errors that may occur. On Error
GoTo 0, turns error trapping off.

The following example ignores errors.


Private Sub drvList_Change()
On Error Resume Next
dirList.Path = drvList.Drive
End Sub
RAISING AN ERROR

The Raise method of the Err object may be used to rethrow the error. This
is particularly useful with class modules, as you can specify the source and a description of the problem.

description = "Unable to process the data


provided"
Err.Raise Err.Number, "myObject", description

The following example handles all errors returned from the InputBox,
except incorrect data types (Error code 13).
Dim age As Integer
On Error GoTo incorrectDataType
age = InputBox("Enter your name", "Age")
Me.Print "You are " & age & " years old"
Exit Sub
incorrectDataType:
If Err.Number = 13 Then
Err.Raise 13
Else
MsgBox Err.description, vbExclamation, "Error"
End If

Summary:

Once you have trapped and handled the error, you need to tell Visual Basic
where to continue with program execution. There are several options
available when an error handling block is entered using On Error Goto label:
Resume
The Resume statement tells VB to continue execution with the line that
generated the error.
Resume Next
Resume Next instructs Visual Basic to continue execution with the line
following the line that generated the error. This allows you to skip the
offending code.
Resume label
This allows you to redirect execution to any label within the current
procedure. The label may be a location that contains special code to handle
the error, an exit point that performs clean up operations, or any other point
you choose.
Exit
You can use Exit Sub, Exit Function, or Exit Property to break out of the
current procedure and continue execution at whatever point you were at
when the procedure was called.
End
This is not recommended, but you can use the End statement to
immediately terminate your application. Remember that if you use End,
your application is forcibly terminated. No Unload, QueryUnload, or
Terminate event procedures will be fired. This is the coding equivalent of a
gunshot to the head for your application.
In addition to these statements, you can also call the Clear method of the Err
object to clear the current error. This is most often used with inline error
handling, as shown below:
Public Sub CreateFile(sFilename As String)

On Error Resume Next


' the next line will raise an error if the file
' doesn't exist, but we don't care because the
' point is to kill it if it does anyway.
Kill sFilename
Err.Clear

' code to create a file

End Sub
This isn't a very robust example. There are many other things besides a file
that doesn't exist that could cause the Kill statement to fail. The file may be
read-only, there may be a network permissions error, or some other problem.
4.3. Apply the debugging and error trapping application.
4.3.1. Construct program using On Error Statement and Err object.
4.3.2. Apply Error-Handling Routines in application.

Please go through experiment 5 to get the ability on constructing program


using On Error Statement and Err object and also applying Error-Handling
Routines in application.

These is several numbers of error available in Visual Basic for error trapping
and handling techniques:
Visual Basic for Applications Reference:
Invalid procedure call or argument (Error 5)
Overflow (Error 6)
Out of memory (Error 7)
Division by zero (Error 11)
Type mismatch (Error 13)
Out of string space (Error 14)
Expression too complex (Error 16)
Can't perform requested operation (Error 17)
Internal error (Error 51)
File not found (Error 53)
Disk full (Error 61)
Path not found (Error 76)
Out of memory (Error 31001)

Experiment: 05

Title: ERROR TRAPPING AND HANDLING

Objective: At the end of the unit you will be able to:

Define the Err object.


Use On Error Statement.
Create error-handling code.
Determine how and where the programme is to continue after the error
is taken care of
The theory:

Error handling is an essential procedure in Visual Basic programming


because it can help make the program error-free. An error-free program can
run smoothly and efficiently, and the user does not have to face all sorts of
problems such as program crash or system hang.

Errors often occur due to incorrect input from the user. For example, the
user might make the mistake of attempting to enter a text (string) to a
box that is designed to handle only numeric values such as the weight
of a person, the computer will not be able to perform arithmetic
calculation for text therefore will create an error. These errors are
known as synchronous errors.

Therefore a good programmer should be more alert to the parts of


program that could trigger errors and should write errors handling code
to help the user in managing the errors. Writing errors handling code
should be considered a good practice for Visual Basic programmers, so
do try to finish a program fast by omitting the errors handling code.
However, there should not be too many errors handling code in the
program as it create problems for the programmer to maintain and
troubleshoot the program later.

Using On Error GoTo Syntax

VB6 supports errors handling syntax, that is the On Error


GoTo program_label structure. Although it has a more advanced error
handling method, we shall deal with that later. The syntax for errors handling
is

On Error GoTo program_label

where program_label is the section of code that is designed by the


programmer to handle the error committed by the user. Once an error is
detected, the program will jump to the program_label section for error
handling.

Exercise 1:

Let's start a new Visual Basic Project, and place a Command Button on the
form. Place the following code into the Click Event Procedure of the form.
Private Sub Command1_Click()
Dim intValue1 As Integer
Dim intValue2 As Integer
intValue1 = 12
intValue2 = 0
Form1.Print intValue1 / intValue2End Sub

Run the program and what the output?

Then add error trapping like shown below:

Private Sub Command1_Click()


On Error GoTo PROBLEM1
Dim intValue1 As Integer
Dim intValue2 As Integer
intValue1 = 12
intValue2 = 0
Form1.Print intValue1 / intValue2
Exit Sub
PROBLEM1:
MsgBox "Error Number:" & Err.Number & vbCrLf & Err.Description
Resume Next
End Sub

Exercise 2:

In this example, we will deal with the error of entering non-numeric data into
the textboxes that suppose to hold numeric values. The program_label here
is error_hanldler. when the user enter a non-numeric values into the
textboxes, the error message will display the the text"One of the entries is
not a number! Try again!". If no error occur, it will display the correct answer.
Try it out yourself.

i) Build a form as shown below:


lblAnswer

lblError

ii) Double-click on the command button and to key-in the procedure in


the space between Private Sub............. End Sub.

iii) Run the project and click the command button. A sample run is
shown below:
Exercise 2:

i) Build a form as shown below:


ii) Double-click on the command button and to key-in the procedure in
the space between Private Sub............. End Sub

Next

Please look carefully at the source code, why we use Resume operator?

In most cases, after dealing with the error, we must find a way to continue
with a normal flow of our program. In some other cases, we want to ignore
the error and proceed as if everything were normal, don't want to bother
the user with some details of the error.

After we have programmatically deal with an error, to resume with the


normal flow of the program, use the Resume operator. After an error has
occurred, to ask the compiler to proceed with the regular flow of the
program, type the Resume keyword.

iii) Run the project and click the command button. A sample run is
shown below:
Exercise 3:

i) Again, build a form as shown below:

ii) Double-click on the command button and to key-in the procedure in


the space between Private Sub............. End Sub

iii) Run the project and click the command button.


iv) What is happening to your program? Explain it.

Exercise 4:

i) Build a form as shown below:

ii) Key-in the procedure as below.


iii) Complete the procedures for each operation (subtraction,
multiplication and division).

iv) Run the project and click the command button. A sample run is
shown below:
PRACTICAL

DESIGN TIME!!!

LAB 5

THINK! THINK! THINK!


Conduct a group of 2 people.

Make an application using the concept you had studied.

Write a program using the On Error GoTo errorHandler structure that


will:

Calculate:

I. Coulombs law

II. Power

III. Star delta

IV. Three phase system

V. Transformer

(Choose any four and please use multiple forms)

Overflow

Type mismatch

Divide by zero
DEC 5062 (VB)- LAB # :

BIL NAMA NO PENDAFTARAN

1.

2.

Rubric for Laboratory


NEEDS NOT
EXCELLENT SATISFACTORY
CRITERIA IMPROVEMENT COMPLETED Weightage Marks
+3 +2
+1 +0
Interface design is Interface design meets Interface design is Interface design has
professional and basic client cluttered, messy, or not been completed
provides user specifications confusing
instructions where and/or Lets others do the
necessary GUI suffers from only Interface design does work.
one of the following: not meet client
Interface design visually distracting specifications Neither copycat nor
exceeds client objects, clashing cheating.
specifications colours, inconsistent GUI suffers from more
Interface

software components, than one of the


Design

GUI satisfies all of thepoor alignment, sizing following: visually 2 /6


following: visually or spacing, non- distracting objects,
attractive objects, standard software clashing colours,
compatible colours, interface conventions. inconsistent graphical
consistent software components, poor
components, great alignment, sizing or
alignment, sizing and spacing, non-standard
spacing, standard software interface
software interface conventions
conventions followed

All properties of Most properties of Minimal properties of Control properties


controls are set to controls are set to controls have been set have not been set
meet specifications meet specifications of and/or controls have
Properties

of the problem. the problem. not been named Lets others do the
Program

work.
2 /6
Use suitable Project runs but
components that Project runs but components used was Neither copycat nor
could suggests the components used was not suitable at all. cheating.
best solutions to not suitable to be used.
problems.
Concepts from class Program code has
Concepts from class Concepts from class are not applied to the not been completed
are applied, Code is are applied, however, program
straight forward, code contains unused Lets others do the
Program Code

consistent, logic uses VB elements work.


the most direct ->variables,
approach available in procedures etc. , code Neither copycat nor 4 /12
VB and does not rely has flow which is cheating.
on programmer jumpy, spaghetti,
patches programmer patches
were applied, or code
contains unnecessary
statements
all requirements met contains 1 run time contains more than 1 Cant be run at all
Error

and runs with no bug or error run time bug or error


errors Lets others do the
Program code contains work.
Program runs major errors and 3.5 /10.5
without errors and produces incorrect Neither copycat nor
produces correct results cheating.
results -and/or-
Significant amounts of
code have not been
completed
The program was The program was The program was The program was 2 /6
Delivery

delivered on time delivered within 24 delivered within 72 more than 3 days


hours of the due date hours of the due date overdue

The student gave an The student completed The student finished The student did not 1 /3
Effort

effort far beyond the the project in an above the project, but it lacks finish the work in a
requirements of the average manner, yet finishing touches or satisfactory
project more could have been can be improved upon manner.
done with little effort.

Can be left to do Needs minimal Required no more Unable to work 2.5 /7.5
Collaboration and Initiative
Self Reliance

alone most of the supervision following supervision following without continuous


time following instruction instruction than might help from lecturer.
instruction. be expected

The whole group The whole group The group did not There was little or 2 /6
worked incredibly worked well together work very well no group
Group

well together together collaboration,


everyone worked
on their own.

*** Project NIL NIL NIL


Embellishme*

embellishment shows
extra work,
challenges the
nt

students 1 /3
programming ability,
is useful to the
program and is well
executed
TOTAL
/60

REMARKS:

References:

https://msdn.microsoft.com/en-us/library/aa716196(v=vs.60).aspx
http://www.virtualsplat.com/tips/visual-basic-debugging.asp

http://www.vb6.us/tutorials/error-handling

http://www.functionx.com/vbaexcel/Lesson26.htm

https://msdn.microsoft.com/en-us/library/aa231079(v=vs.60).aspx

You might also like