This lesson is part of an ongoing tutorial. The first part is here: Design
The third category of errors are the Logic errors. These can be thought of
as coding errors. Your coding errors. They can be quite tricky to track down,
and have you tearing your hair out with frustration. You will often hear yourself
saying “But that should work! Why won’t it!”
Add another button to the form tou created in the first
part, and try this code as an example of a logic error:
Dim x As Integer
Dim y As Integer
Dim answer As Integer
x = 10.5
y = 3
answer = x * y
TextBox1.Text = answer
When you’ve added the code to your button, run your programme and test it out.
Before you click the button, what answer did you expect to get?
You’d think that 10.5 multiplied by 3 would give you the answer 31.5. Click
your button. The answer that appears in your textbox is 30!
This is a logic error: when you don’t get the answer you thought you’d get.
The problem, if you were paying attention during the variable types sections,
is that we are trying to put floating point numbers into an Integer variable
type. The Integer variable only works with whole numbers. When you assign 10.5
to the variable x, the point 5 on the end gets chopped off. So only the 10 gets
stored in x. 10 times 3 is thirty, and this is the answer that appears in the
But the point is that VB.NET did not raise a Design-time error. Nor did it
raise a Runtime error. The programme executed, and did not “bug out”
on us. It just didn’t give you the answer you expected – it was a logic error.
Logic errors can be fairly simple to track down and solve. (The problem above
can be solved by changing the variable types from Integer to Single or Double.)
But they can also be quite difficult to track down. Especially as your code
gets longer and longer. Here’s another example of a logic error.
Erase the code you have for button2, and add the following instead:
Dim i As Integer
Dim LetterCount As Integer
Dim strText As String
Dim letter As Char
strText = “Debugging”
i = 1 To strText.Length – 1
letter = strText.Substring(1)
If letter = “g” Then
LetterCount = LetterCount + 1
TextBox1.Text = “G appears ” & LetterCount & ” times”
All the code does is to try and count how many times the letter “g”
appears in the word “Debugging”. We’re using a For loop, and Substring
to get one letter at a time. This single letter is then placed inside the variable
called letter. An If Statement is used to check if the letter is a “g”.
If it is, we increment the LetterCount variable. The answer we’re expecting
in the textbox is 3. Except, we don’t get 3. We get zero:
There were no wiggly lines and therefore no Build errors. When
the button was clicked, a Runtime exception did not crash the programme. So
that leaves a logic error. But where is it?
In the next part, you’ll learn how to use VB .NET’s inbuilt tools
to help you track down logic errors.
Kaynak : https://www.homeandlearn.co.uk/NET/nets5p5.html ‘sitesinden alıntı