You are on page 1of 109

Visual Basic Looping

Data File
& Error Handling
Module 3
Visual Basic Looping
• Used for operations that are repeated for some
number of times.

• Loop repeats until some specified condition at


the beginning or end of the loop is met.

• Looping statements:
– Do loop variations
• do while, do until, do loop while, do loop until
– For loop
– While loop
Loops Constructs
• Pretest Loops:
Do While (or Until) condition
body of the loop
Loop

• Posttest Loops:
Do
body of the loop
Loop While (or Until) condition
Pre-Test Structures
Do While - Loop
Do Until – Loop
While – End While
For - Next
Post-Test Structures
Do - Loop While
Do - Loop Until
• Do While - Loop Structure
<Initialization statement>
Do While <condition - TRUE>
:
: < write TRUE statements here…>
[ Exit Do ]
Loop

• Do Until - Loop Structure


<Initialization statement>
Do Until <condition - FALSE>
:
: < write FALSE statements here…>
[ Exit Do ]
Loop
• Do - Loop While Structure
<Initialization statement>
Do
: <perform statements once,
: write TRUE statements here…>
[ Exit Do ]
Loop While <condition - TRUE>

• Do - Loop Until Structure


<Initialization statement>
Do
: <perform statements once,
: write FALSE statements here…>
[ Exit Do ]
Loop Until <condition - FALSE>
• While –End While Structure
<Initialization statement>
While <condition - TRUE>
:
: write TRUE statements here…>
[ Exit While ]
End While

• For – Next Structure

For <var> = <initial> to <final> [Step <value>]


: <statements here…>
[Exit For]
[Continue For]
Next [<var>]
Exercise #1
• Display sequence of numbers
from 1 to 5 using Msgbox()

X=1 X=1
Do While X <= 5 Do
Msgbox (“Number ” & X) Msgbox (“Number ” & X)
X=X+1 X=X+1
Loop Loop While X <= 5

X=1 X=1
Do Until X > 5 Do
Msgbox (“Number ” & X) Msgbox (“Number ” & X)
X=X+1 X=X+1
Loop Loop Until X > 5
Exercise #1
• Display sequence of numbers from 1 to 5 using
Msgbox()
X=1
While X <= 5
Msgbox (“Number ” & X)
X=X+1
End While

For X = 1 to 5
Msgbox (“Number ” & X)
Next X
Exercise #2
• Display sequence of numbers from 10 to 25
Do While - Loop Do – Loop While
X = 10 X = 10
Do While X <= 25 Do
Msgbox(X) Msgbox(X)
X=X+1 X=X+1
Loop Loop While X <= 25

Do Until - Loop Do - Loop Until


X = 10 X = 10
Do Until X > 25 Do
Msgbox(X) Msgbox(X)
X=X+1 X=X+1
Loop Loop Until X > 25
Exercise #2
• Display sequence of numbers from 10 to 25

Using While Using For-Next


X = 10 For X = 10 to 25
While X <= 25 Msgbox(X)
Msgbox(X) Next X
X=X+1
End While
Exercise #3
• Rewrite the code to output numbers from 25 down to 10.
Do While - Loop Do Until - Loop
X = 25 X = 25
Do While X >= 10 Do Until X < 10
Msgbox(X) Msgbox(X)
X=X-1 X=X-1
Loop Loop
Do - Loop While Do - Loop Until
X = 25 X = 25
Do Do
Msgbox(X) Msgbox(X)
X=X-1 X=X-1
Loop While X >= 10 Loop Until X < 10
Exercise #3
• Rewrite the code to output numbers from 25 down to 10.
Using While Using For - Next
X = 25
While X >= 10 For X = 25 to 10 Step -1
Msgbox(X) Msgbox(X)
X=X-1 Next X
End While
Your Turn…
Write codes that print all the odd numbers from 1
to 50 using the Do While - loop structure.
Exercise #4
Write codes that compute the squares and
cubes of the integers from 1 to 10 with the
following output. Note: Use Listbox, Property:Items
Number Square Cube
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
Solution Using Do-Loop
Private Sub Button_Click(… )
Dim no As Integer = 1
Dim Sq, Cu as Integer
Do
Sq = no^2
Cu = no^3
ListBox1.Items.Add(no & vbTab & Sq & _
vbTab & Cu)
no = no + 1
Loop Until no = 11
End Sub
Solution Using While
Private Sub Button_Click(… )
Dim no As Integer = 1
Dim Sq, Cu as Integer
While no<=10
Sq = no^2
Cu = no^3
ListBox1.Items.Add(no & vbTab & Sq & _
vbTab & Cu)
no = no + 1
End While

End Sub
Your turn…
Write codes that print the degrees Celsius from 5
to 45 (step 5) with their equivalent degrees
Fahrenheit as follows: (Use List box)
Celsius Fahrenheit
5 41.00
10 50.00
15 59.00
20 68.00
25 77.00
30 86.00
35 95.00
40 104.00
45 113.00
Exercise #5
• The bank charges 12% simple interest on the amount
per annum. Write a VB program that allows the user
to input for the amount loan and the number of years
to pay. Compute and display the lump sum amount
for each year.

Formula: Amt = P (1 + r t)
where: Amt – lump sum amount
P – Principal amount
r – interest rate (12%)
t – # of years
Solution
Private Sub Compute_Click()
Dim Amt, P As Single, t As Integer
Const r as Single = 0.12
P = TextBox1.Text
LB.Items.Add(“Year" & vbTab & “Amount/Year")
t=1
Do While t <= Textbox2.Text
Amt = P * ( 1 + r * t)
LB.Items.Add(t & vbTab & Amt)
t=t+1
Loop
End Sub
Exercise #6
• A bank offers a car loan at the rate of 15% compounded
monthly. Write a program allowing the user to input for the
loan amount of the car and the period of years to pay.
Compute and display the monthly payments to amortize
the loan and determine the total amount at the end of the
period.
compounded interest
Formula: i
12
n = years x (12 months)

PA
1  i   1
n

i 1  i 
n
Private Sub Compute_Click() Solution
Dim P, int, TotAmt, Amort As Single, term, m As Integer
P = TextBox1.Text
term = NUpDwCtr.Value * 12
int = 0.15 / 12
LB.Items.Add("Month" & vbTab & "Annuity" & vbTab & _
"Total Contribution")
Amort = (P * int * (1 + int) ^ term) / ((1 + int) ^ term - 1)
m=1
While m <= term
TotAmt = TotAmt + Amort
LB.Items.Add(m & vbTab & Amort & vbTab & TotAmt)
m=m+1
End While
End Sub
Seatwork…
Write a code that prints the angles in degrees
from 0 to 80 (step 10) and its equivalent Sine()
and Tan() in radians as follows: (Use List box)
DataGridView Component
• Displays data in a customizable grid.
• Some of DataGridView Properties:
– AllowUserToAddRows
– AllowUserToDeleteRows
– Columns
– Rows
– EditMode
– MultiSelect
– ColumnHeadersVisible
– RowHeadersVisible
Use of DataGridView
• Using DataGridView, write a code that
computes and displays the squares and cubes
of the integers from 1 to 10 with the following
output.
Private Sub Button_Click() Solution Code
Dim No, Sq, Cu As Integer
DataGridView1.Columns.Clear()
DataGridView1.Columns.Add(No, "Number")
DataGridView1.Columns.Add(Sq, "Square")
DataGridView1.Columns.Add(Cu, "Cube")
No = 1
Do While No <= 10
Sq = No ^ 2
Cu = No ^ 3
DataGridView1.Rows.Add(No, Sq, Cu)
No = No + 1
Loop
End Sub
Retrieve Data from DataGridView
x=0
Do While x <= DataGridView1.Rows.Count-1
No = DataGridView1.Rows(x).Cells(0).Value
Sq = DataGridView1.Rows(x).Cells(1).Value
Cu = DataGridView1.Rows(x).Cells(2).Value
MsgBox(No & “ ” & Sq & “ ” & Cu)
x=x+1
Loop
Assignment
Example: Use of Exit Do
• This code displays numbers from 1 to 5 even if
the final value of X is 10.

X=1
Do While X <=10
Msgbox (X)
if X = 5 then Exit Do
X=X+1
Loop
Example: Use of Exit While
• This code displays numbers from 1 to 5 even if
the final value of X is 10.

X=1
While X <=10
Msgbox (X)
if X = 5 then Exit While
X=X+1
End While
Example: Use of Exit For
• This code displays numbers from 1 to 5 even if
the final value of X is 10.

For X = 1 To 10
Msgbox (X)
if X = 5 then Exit For
Next X
Assignment
Exercise #9
Make a program that computes the distance a
body falls in feet per second, for the first 5
seconds of free fall as given by the equation:
S = ½ at2 where: S = the distance in feet
a = acceleration due to gravity (32 ft/sec2)
t = time in seconds
• Output:
Time(in sec) Distance(in ft)
1 16
2 64
3 144
4 256
5 400
Solution
Private Sub Calculate_Click()
Dim tym As Integer, dist As Single
DataGridView1.Columns.Clear()
DataGridView1.Columns.Add(tym, "Time (in sec)")
DataGridView1.Columns.Add(dist, "Distance (in ft)")
tym =1
While tym <= 5
dist = 1 / 2 * 32 * tym ^ 2
DataGridView1.Rows.Add(tym, Format(dist, "f"))
tym = tym + 1
End While
End Sub
Exercise #10
The x and y coordinates, as function of time t of a projectile
fired with an initial velocity v at an angle  with respect to
the ground is given by:
x = v t cos() y = v t sin() – ½ gt2
Using these formulas, write code that allows the user to
input for the initial velocity (say 350 m/sec ) at an angle (say
25 degrees). Display a table of x (distance travelled) and y
(height) values for a projectile fired at time interval 0 to the
total time of flight (that is: t = 2 v sin() / g ) seconds with
increments of ½ second.

Hint: Remember to convert to radian measure.


Expected Output:
Solution
Private Sub Compute_Click()
Dim t D, H, TFlight, Vo, Angle As Single
Const g As Single = 9.80665

Vo = TextBox1.Text
Angle = TextBox2.Text
DG1.Columns.Clear()
DG1.Columns.Add(t, "Time")
DG1.Columns.Add(D, "Distance")
DG1.Columns.Add(H, "Height")
TFlight = 2 * Vo * Math.Sin(Radians(Angle)) / g
TextBox3.Text = Format(TFlight, “n2")
Solution
t=0
While t <= TFlight
D = Vo * t * Math.Cos(Radians(Angle))
H = Vo * t * Math.Sin(Radians(Angle)) - 0.5 * g * t ^ 2
DG1.Rows.Add(t, Format(D, “f"), Format(H, “f"))
t = t + 0.5
End While
t = TFlight
D = Vo * t * Math.Cos(Radians(Angle))
H = Vo * t * Math.Sin(Radians(Angle)) - 0.5 * g * t ^ 2
DGV1.Rows.Add(t, Format(D, “f"), Format(H, “f"))
End Sub
Exercise #11
Given different values (assume all are integers)
listed in the list box, determine the sum of all
the values.

Private Sub Compute_Click()


Dim total, ctr As Integer
For ctr = 0 To ListBox1.Items.Count - 1
total = total + ListBox1.Items(ctr)
Next ctr
TextBox1.Text = "Sum is " & CStr(total)
End Sub
Exercises
Tell how many times does each of the following loops
iterate and what is the final value of the variable ‘X’ in
each case?
1. X = 5 3. X = 60
While X <=30 Do
X=X+1 X = X - 10
End While Loop Until X = 40

2. X = 10 4. X = 100
Do While X <= 50 Do Until X > 70
X=X+5 X = X - 20
End Do Loop
Exercises
Tell how many times does each of the following loops
iterate and what is the final value of the variable ‘X’ in
each case?
5. X = 15 7. X = 75
While X <=45 Do
X=X+5 X = X + 10
if X >=30 then Exit While Loop Until X <= 10
End While

6. X = 100 8. X = 100
Do While X > 75 Do Until X > 70
X=X–5 X = X - 20
if X > 75 then Exit Do if X = 75 then Exit Do
End Do Loop
Exercises
Tell how many times does each of the following for next
loops iterate and what is the final value of the variable
‘X’ in each case?

9. For X = 0 to 10 11. For X = 20 to 0 Step -2


Next X Next X

10. For X = 0 to 10 Step 2 12. For X = 0 to 12 Step 3


Next X Next X
Variation of For-Next
• Syntax:
For Each <var> In <list>
<INSTRUCTIONS>

Next

• Example:
Dim str As String
For Each str In My.Computer.FileSystem.GetDirectories("C:\")
Listbox1.Items.Add(str)
Next
Looping Exercises
Exercise 1
• Conversion of decimal number to binary:
Read a decimal number and convert the
number to its equivalent binary number.
Validate data entry for the decimal number.
Solution: Decimal to Binary

Private Sub TextBox1_KeyPress()


If ( e.KeyChar < “0” Or e.KeyChar > “9” ) _
And (e.KeyChar <> Chr(Keys.Back) ) Then
e.KeyChar = Chr(Keys.Clear)
End If
End Sub
Recall: Decimal to Binary Conversion
• Steps/Algorithm:
1. Assign Decimal number to variable Q

Q = Textbox1.text

2. Repeatedly divide Q by the base (2) until the


quotient is zero(0).

do until Q = 0
Q=Q\2
loop
Recall: Decimal to Binary Conversion
• Steps/Algorithm:

3. For each division operation, tally the remainder.

st = (Q Mod 2) & st

4. If the quotient is already zero, write all the tallied


remainders by reading them in upward direction.

TextBox2.Text = st
Code for Conversion
Private Sub Conversion_Click()
Dim Q As Integer
Dim st as String = “”
Q = TextBox1.Text
Do Until Q = 0
st = Q Mod 2 & st
Q=Q\2
Loop
TextBox2.Text = st
End Sub
Seatwork
• Develop codes that allow user to input for the
decimal number. Convert the number into its
equivalent:
– Octal number
– Base 9
Exercise 2
• Conversion of Decimal number to Hexadecimal:

Private Sub TextBox1_KeyPress()


If ( e.KeyChar < “0” Or e.KeyChar > “9” ) _
And (e.KeyChar <> Chr(Keys.Back) ) Then
e.KeyChar = Chr(Keys.Clear)
End If
End Sub
Private Sub Conversion_Click()
Dim Q As Integer, st as String = “”
Q = TextBox1.Text
Do Until Q = 0
Select Case Q Mod 16
case 10 : st = “A” & st
: : : :
case 15 : st = “F” & st
case Else
st = Q Mod 16 & st
End select
Q = Q \ 16
Loop
TextBox2.Text = st
End Sub
Seatwork
• Develop codes that allow user to input for the
decimal number. Convert the number into its
equivalent:
– Base 13
– Base 20
Exercise 3
• Binary to Decimal number conversion:
Read an integer binary number. Convert the
number to its equivalent decimal. Validate data
entry for the binary number.
Data Entry Validation
Private Sub TextBox1_KeyPress()
If (e.KeyChar < “0” Or e.KeyChar > “1”) _
And (e.KeyChar <> Chr(Keys.Back)) Then
e.KeyChar = Chr(Keys.Clear)
End If
End Sub
Recall Mid() function
• Mid (“string”, <start position>, [no of char])
– Retrieves text within a string

Example:
Dim Str As String = “1101001”
bit = Mid(Str, 1, 3)
-> returns “110”
bit = Mid(Str, 7, 1)
-> returns “1"
bit = Mid(Str, 8,1)
-> Error… should not exceed length
Binary to Decimal Code
Private Sub Button1_Click()
Dim x, y, bit, total As Integer
y = Len(TextBox1.Text)
For x = 0 To y - 1
bit = Mid(TextBox1.Text, y - x, 1)
total = total + 2 ^ x * bit
Next x
TextBox2.Text = total
End Sub
Seatwork
1. Do the integer Octal to decimal conversion
code. Refer your answer to binary to decimal
code.

2. Revise the code to convert Base 6 integer


number to Decimal number.

3. Write the code for Hexadecimal to decimal


integer conversion.
Hexadecimal to Decimal
Solution
Private Sub TextBox1_KeyPress()
If (e.KeyChar < "0" Or e.KeyChar > “9") And _
(e.KeyChar <> Chr(Keys.Back)) And _
(e.KeyChar < "A" Or e.KeyChar > "F") Then
e.KeyChar = Chr(Keys.Clear)
End If
Private Sub Button1_Click()
Dim x, y, total As Decimal, bit As String
y = Len(TextBox1.Text)
For x = 0 To y - 1
bit = Mid(TextBox1.Text, y - x, 1)
Select Case bit
Case "A" : total = total + 16 ^ x * 10
Case "B" : total = total + 16 ^ x * 11
Case "C" : total = total + 16 ^ x * 12
Case "D" : total = total + 16 ^ x * 13
Case "E" : total = total + 16 ^ x * 14
Case "F" : total = total + 16 ^ x * 15
Case Else
total = total + 16 ^ x * bit
End Select
Next x
TextBox2.Text = total
End Sub
The Data File
File I/O
Steps in creating and accessing a
Sequential File in VB
1. Use text editor to create the file with file
extension .txt (use Notepad program).
Steps in creating and accessing a
Sequential File in VB
2. Open the file in the VB project before
data can be input/output from/to it.
Syntax:
FileOpen (n,“filename”,OpenMode.Input)
where:
filename – includes the drive and folder where
the file is located.
n – number between 1 and 511
OpenMode.Input – indicates that the file is
opened for reading data items from the file.
Steps:
• Example:
FileOpen(10,“c:\Number.txt”,OpenMode.Input)

FileOpen(5, “x:\Car.txt”, OpenMode.Input)

Dim FName as String


FName = Inputbox(“Type File name:”)
FileOpen(25,Fname,OpenMode.Input)
Steps in creating and accessing a
Sequential File in VB
3. Read (Input) each data from the sequential
file. You can use looping to read each data.
Syntax:
Input(n,variable)
Example:
Input(10, IntX)
Input(5, Studname)
Input(5, Score1)
Input(5, Score2)
Steps in creating and accessing a
Sequential File in VB
4. Lastly, close the sequential file.

Syntax:
FileClose(n)

Example:
FileClose(10)
FileClose(5)
Sample Problem #1
• Read all the integer values in the file
“location\Scores.txt”. Display all numbers read
using the list box and determine and display
the sum of all the numbers.
Solution
Private Sub DisplayCompute_Click( )
Dim Idata, sum As Integer
ListBox1.Items.Clear()
FileOpen(10, “location\Scores.txt", OpenMode.Input)
Do while not ( EOF(10) )
Input(10, Idata)
ListBox1.Items.Add(Idata)
sum = sum + Idata
Loop
TextBox1.Text = sum
FileClose(10)
End Sub
Solution
Private Sub DisplayCompute_Click( )
Dim Idata As String
ListBox1.Items.Clear()
FileOpen(10, “location\Scores.txt", OpenMode.Input)
Do while not ( EOF(10) )
Input(10, Idata)
ListBox1.Items.Add(Idata)
Loop
FileClose(10)
End Sub
Sample Problem #2
• A sequential file has an unknown number of
records. Each line in the file contains the ff.
information in this order: Student name, and
with his/her 3 quiz scores obtained. Design
and write code that will read this file and
display each line in a list box.
Solution
Private Sub btnLOad_Click()
Dim Stneym, Fname As String
Dim sc1, sc2, sc3 As Integer
ListBox1.Items.Add("Student Name" & vbTab & "Quiz1" & _
vbTab & "Quiz2" & vbTab & "Quiz3")
Fname = “d:\students.txt"
FileOpen(15, Fname, OpenMode.Input)
Do Until EOF(15)
Input(15, Stneym)
Input(15, sc1)
Input(15, sc2)
Input(15, sc3)
ListBox1.Items.Add(Stneym & vbTab & sc1 & _
vbTab & sc2 & vbTab & sc3)
Loop
FileClose(15)
End Sub
Sample Problem #2b
• Revise Program in #2 so that the students
names are listed in a ComboBox as shown
below.
Private Sub Form1_Load() Solution
Dim Stneym, Fname As String
Dim sc1, sc2, sc3 As Integer
ComboBox1.Items.Clear()
FileOpen(15, "d:\students.txt", OpenMode.Input)
Do Until EOF(15)
Input(15, Stneym)
Input(15, sc1)
Input(15, sc2)
Input(15, sc3)
ComboBox1.Items.Add(Stneym)
Loop
FileClose(15)
End Sub
Sample Problem #3
• Revise the program in #1 in such a way that it
will also determine the lowest and the highest
numbers entered.
Solution
Private Sub Determine_Click( )
Dim IData, LN, HN, sum As Integer
FileOpen(10, “d:\Number.txt", OpenMode.Input)
Input(10, IData)
ListBox1.Items.Add(IData)
LN = IData ‘let the 1st number to be the HN and LN
HN = IData
sum = sum + IData
Do Until EOF(10)
Input(10, IData)
ListBox1.Items.Add(IData)
If LN > IData Then LN = IData
If HN < IData Then HN = IData
sum = sum + IData
Loop
Solution (cont.)
TextBox1.Text = sum
TextBox2.Text = LN
TextBox3.Text = HN
FileClose(10)
End Sub
Sample Problem #4
• Revise the code in Problem #2b so that you
will allow the user to input the name of the file
and its location using Inputbox( ) function.

• Use:
fname = InputBox (“Input the filename for data file”)
FileOpen(10, fname, OpenMode.Input)

• Also, compute and display the average quiz


scores of each student.
OpenFileDialog component
• A non-visible component that displays a dialog
box in which the user is prompted to open a
file.
Example
• This command will show the OpenFileDialog
box. OpenFileDialog1.ShowDialog()
Example
• This code will return the name of the file that is
selected by the user.
If OFD.ShowDialog = DialogResult.OK Then

fname = OFD.FileName
FileOpen(5, fname, OpenMode.Input)

EndIf
Sample
Properties of
OpenFileDialog
DefaultExt

Filename

Filter

InitialDirectory

Title
Writing data to the Sequential File
Writing data to the sequential File
• Function for output:
FileOpen(n, “filename”, OpenMode.Output)

• Function to add a new record at the end of the


file:
FileOpen(n, “filename”, OpenMode.Append)

• Function to store data to the file:


Writeline(n, variable list)
Sample Problem
• Revise the code in Problem #4 so that the user
can add new student information by clicking
the Add button.
Solution
Private Sub AddBtn_Click()
Dim Stneym, Fname As String
Dim sc1, sc2, sc3 As Integer
Stneym = TextBox1.Text
sc1 = TextBox2.Text
sc2 = TextBox3.Text
sc3 = TextBox4.Text
Fname = "c:\students.txt"
FileOpen(1, Fname, OpenMode.Append)
WriteLine(1, Stneym, sc1, sc2, sc3)
FileClose(1)
End Sub`
SaveFileDialog()
A non-visible component that displays a dialog
box in which the user is prompted to save a file.
Example
• This command will show the SaveFileDialog
box.
SaveFileDialog1.ShowDialog()
Example
• This code will return the name of the file that is
selected by the user.
If SFD.ShowDialog = Windows.Forms.DialogResult.OK Then

fname = SFD.FileName.ToString
FileOpen(5, fname, OpenMode.Output)

EndIf
Case Study 1
• Problem: You’ve been hired by a law firm that is working on
a sex discrimination case. Your firm has obtained a file of
incomes, “gender.dat”, which contains the salaries for every
employee in the company being sued. Each salary amount
is preceded by “F” for female or “M” for male. As a first pass
in the analysis of this data, you’ve been asked to compute
the average income for females and the average for males.
The output should be saved in a file to be reviewed later.
• Testing: Given the ff. data in file gender.dat:

• Output: The program should write the ff. in


the file `“results.dat”.
Private Sub Button1_Click() Solution
FileOpen(1, “Gender.dat”, OpenMode.Input)
Do Until EOF(1)
Input(1, gender)
Input(1, Salary)
If gender = "F" Then
FIncom = FIncom + Salary
Female = Female + 1
Else
MIncome = MIncome + Salary
Male = Male + 1
End If
Loop
FileClose(1)
Solution
FAve = FIncom / Female
MAve = MIncome / Male
FileOpen(5, “Results.dat”, OpenMode.Output)
WriteLine(5, Fem & " females with an average income of :“ _
& Format(FAve, "c"))
WriteLine(5, Mal & " males with an average income of :" _
& Format(MAve, "c"))
FileClose(5)
End If
End Sub
Case Study #2
• You are putting together a music CD for a party.
You’ve arranged a list of songs in the order in which
you want to play them. However, you would like to
minimize the empty space (the CD plays for 67
minutes). So you want to figure out the total time for a
group of songs and see how well they fit. Write and
design a VB application to help you do this. For
example, if a song takes 7 minutes and 42 seconds
to play, the data entered for that song would be 462.
Case Study #2 (cont.)
• Assume that the list of songs is stored in
MUSIC.txt with the following format: Song
number and playing (song) time (in sec)
• After reading all the data from the text file,
display the ff. info using listbox:
Error Handling &
Debugging in VB 2005
Types of Error
• Design-time error

• Runtime errors

• Logic errors
Design-time error
• Known as a syntax error
• VB compiler doesn't understand your code.
• Easy to track down in VB because you will
see a blue wiggly/squiggly line pointing them
out.
• Attempting to run the program will display a
dialogue box popping up telling you that there
were Build errors.
Runtime errors
• Errors occur when the program is running.
• Exists when the program tries to do something
it shouldn't be doing.
– Example: Trying to access a file that doesn't exist.

• Usually causes your program to crash.


• As a programmer, you should write code to
trap runtime errors. It's your job to predict
these errors and write a code accordingly.
Example: Runtime error #1
a. Dim Num1, Num2 As Integer
Num1 = 10
Num2 = 0
TextBox1.Text = Num1 / Num2
Example: Runtime error #2
b.
FileOpen(5, "c:\test10.txt", OpenMode.Input)
Example: Runtime error# 3
c. Dim Num As Integer
Num = TextBox1.Text
Logic errors
• Occur when the program while is running.
• Happen when your code doesn't quite
behave the way you thought it would.
• Logic errors tend not to crash your program,
but they will ensure that it doesn't work
properly.
Example: Logic errors
a. X = 10
Do While X > 5
Area = Math.PI* X^2
X=X+1
Loop

b. Dim x As Single= 10.5


Dim y As Integer = 3, Answer As Integer

Answer = x * y
TextBox1.Text = Answer
Try … Catch Statement
Solution to Runtime Error
Try … Catch Statement
• Built-in class (command) that deals with errors.
• The Class is called Exception. When an exception
error is found, an Exception object is created.
Syntax:
Try
<Instruction codes>
Catch ex As Exception
<Instruction codes>
[Finally ‘ ---Optional part of code
Instruction codes]
End Try
Try … Catch Statement
• Try
– means "Try to execute this code".
• Catch
– means "Catch any errors here". The ex is a
variable, and the type of variable it is an Exception
object.
• Finally
– is always executed, whether an error occurs or not.
It is used to perform any cleanup operations that
are needed.
• End Try
Example #1: Try… Catch
Try
FileOpen(5, "c:\test10.txt", OpenMode.Input)
Catch ex As Exception
Messagebox.Show (“File not found.”)

or
Msgbox(ex.Message) ------
End Try
Example #2: Try… Catch
Try
FileOpen(5, "c:\test10.txt", OpenMode.Input)
Catch ex As System.IO.FileNotFoundException
Messagebox. Show (“File not found.”)
Finally
Fileclose(5)
Exit Sub
End Try
Example #3: Try… Catch
Try
X = Inputbox(“Input Number”, “Data Entry”)
Catch ex As System.IO.FileNotFoundException
MsgBox(“Operation Cancelled…”)
Finally
Fileclose(5)
Exit Sub
End Try
End of Presentation

You might also like