Professional Documents
Culture Documents
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.
i. syntax error
Occurs when the rule of VB syntax are violated. Example of syntax error is
using the reserved keyword as variable name:
If (mark>=90)
Txtmarkh.Text= You are excellent
return 0;
It occurs when the program does not behave as intended, due to poor logic
or incorrect implementation
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 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 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.
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)
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.
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
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.
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
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.
lblError
iii) Run the project and click the command button. A sample run is
shown below:
Exercise 2:
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.
iii) Run the project and click the command button. A sample run is
shown below:
Exercise 3:
Exercise 4:
iv) Run the project and click the command button. A sample run is
shown below:
PRACTICAL
DESIGN TIME!!!
LAB 5
Calculate:
I. Coulombs law
II. Power
V. Transformer
Overflow
Type mismatch
Divide by zero
DEC 5062 (VB)- LAB # :
1.
2.
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
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
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
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