Debugging and Error Handling
© Peter Bilbie 2010

Contents

Introduction 3

Syntax errors 3

Runtime Errors 5

Logical or semantic errors 7

Pythagoras’ Theorem 7

Exercise 1 7

The Debugger 10

Error Handling 12

Exercise 2 13

Extension to Exercise 2 13


Debugging and Error Handling

Introduction

As you will have seen last session it is very easy to create errors in your code and if you have had any experience of development you will know that testing is the lengthiest of all tasks. This week we will look at the types of error you could encounter and how to deal with them.

A bug is a coding error that prevents programs from functioning correctly and the bigger the program the more chances of there being errors. There are three basic error types

·  Runtime errors

·  Syntax errors

·  Logic or semantic errors

Syntax errors

These are errors in the language structure i.e. typo errors or using the wrong names when calling up variables or controls. These are usually picked up by the compiler when you try to run the program. The example below code shows an object - textbox – being assigned to an integer variable

This is a common error, especially with novice programmers as it is the Text property value that needs to be assigned to the integer variable not the text box object itself. A blue squiggly line appears underneath the erroneous code but if we try to run the code above the following message is displayed:

If Yes is clicked then the compiler will ignore any code written since the last compilation. If ‘No’ is clicked the program will return to the code window

Any syntax errors are picked up as you write them in the Error List window at the bottom of the IDE – see below

If you double-click on the error message the line of code that is causing the error is highlighted – see below:

Using the Intellisense feature can help prevent syntax errors such as the one above. For example If you begin to type part of the name of a control i.e. txtF and press Ctrl-Space (Intellisense), a list is displayed showing all possible options – see below

If there is only one possible choice then Intellisense will automatically complete the name. If no options are shown then the name has been miss-spelt or does not exist. Also if you do not use Intellisense and mistype a control name and add the period (full stop) no properties or methods are displayed.

Remember, it doesn’t matter how quick and accurate you are at typing letters/reports etc it is still possible that you could make typo errors whilst typing non-standard English used in coding a program. Intellisense will increase your typing efficiency when you get used to using it

Runtime Errors

Runtime errors can occur when the syntax is correct i.e. it has compiled successfully but something occurs whilst the program is running that causes it to crash. This problem could occur for many reasons including:

·  A file required by the program has been deleted or is unavailable

·  The user is allowed to enter the wrong data i.e. user input has not been validated

Using the Variables exercise from the previous session I have tried to input an alpha character – string data type – in a calculation that requires integer values to be input.

When the program is executed a dialog box is displayed – see below.

The erroneous line of code is highlighted in yellow and the message at the top of the dialog box gives the user a ‘basic idea’ of what type of error has occurred. To obtain a more detailed description of the error click on View Detail in the Action area of the dialog box – see below:


Click on the ‘+’ sign to get a very detailed explanation for the error – see below

When you have read the error message click OK and also close the error type dialog box. The program is still running and a message is displayed in the Immediate Window at the bottom of the screen

Hang the cursor over the text property of the textbox and the value of the property is displayed

Stop the program running by clicking on the blue square on the icon menu next to the start green triangle – see below:

Correct the error. In the example above it is a user input error that has caused the program to crash rather than a coding error. However, we must ensure that the user is only allowed to enter the correct data by ‘Validating’ user input – this will be covered in a later session

Logical or semantic errors

These are mistakes in the meaning of your code i.e. it does not perform as you expect i.e. assigning incorrect values to variables or a formula is written incorrectly. This type of error is usually identified during testing when the results of operations or calculations are compared to known values. For example, if we created a program that calculated the longest side of a right-angled triangle (the hypotenuse) from the values of the two shorter sides (the perpendicular and base) using Pythagoras’ theorem we could check the program is outputting the correct value by using the values 3 and 4 for the two shorter sides and the result should be 5. This is because right-angled triangles in the ratio 3:4:5 are constant.

Pythagoras’ Theorem

The square of the hypotenuse is equal to the sum of the squares of the two adjacent sides’

The formula to work out the hypotenuse given the perpendicular and base is:

Hypotenuse = √Base 2 + Perpendicular 2

Exercise 1

Create a program that will allow the user to enter the perpendicular and base dimensions of a right-angled triangle into two textboxes. Provide a button and using the formula above code the click event to calculate the hypotenuse of the triangle. Use the 3:4:5 constant to test your calculations

Written in VB syntax is

Hypotenuse = (base ^ 2 + perpendicular ^ 2) ^ 0.5

The addition of the squared base and perpendicular are evaluated before the square root is calculated – see Variables handout notes on operator precedence

Create a new form in your MDI form and call it FrmPythagoras. Add a menu item for opening the new form. To the form add 3 textboxes named txtPerpendicular, txtBase and txtHypotenuse, a button named btnCalculate and three labels for the textboxes – see below

Add the following code to the Click Event of the calculate button

Private Sub btnCalculate_Click(…

Dim hyp, perp, base As Single

perp = txtPerpendicular.Text

base = txtBase.Text

hyp = ((perp ^ 2) + (base ^ 2)) ^ 0.5

txtHypotenuse.Text = hyp

End Sub

If we run the program and add 3 to the perpendicular textbox, 4 to the base textbox and click ‘Calculate’ the answer 5 should be shown in the hypotenuse textbox – see below:


If we enter any values in the perpendicular and base textboxes but maintain the same 3:4:5 ratio, the hypotenuse should have a corresponding value i.e. 12:16:20, 15:20:25 etc – see below:

What happens if the formula had been incorrectly written i.e. not bracketed the expression correctly i.e.:

hyp = perp ^ 2 + base ^ 2 ^ 0.5

The calculation would not crash but would return the following:

We can check where the code logic has gone awry by using the Debugger

The Debugger

It is an easy task to rectify the problem above as we have forced the error. However, I have seen students make the exact same error in a program and they have spent hours trying to identify where they have gone wrong.

To help us with logical error problems we use the Debugging Tool to allow us to step through the program whilst it is running. To do this, find a suitable place in your code that you want to start debugging i.e. the beginning of the click event of the ‘Calculate’ button, and click in the grey margin of the code window – a brown circle will be displayed and the line of code will be highlighted in the same colour – see below

If we run the program and add two numbers to the perpendicular and base textboxes and then click the ‘Calculate’ button the program we will be able to step into the code at the place where you entered the brown circle – see below:

The line colour will have changed to yellow and a yellow arrow can be seen in the brown circle. To step through the code press F10 and each time you press F10 it will move to another line. At ay stage you can hang the cursor over any variable to check its value, however each line of code is not evaluated until you have moved past the line by clicking F10 – see below:

On the line perp =0.0

After perp = 3.0

If we continue to evaluate each line, when we come to the calculation we can see the values of all the variables and it is obvious from the hypotenuse value that the problem lies with the formula

Using the wrong operator precedence is the cause of many logical errors.

You can stop the debugger by clicking on the square, blue stop debugging button on the main menu – see below

Error Handling

The error messages from runtime errors are meant for the developer not the end user. To prevent this problem we need to rigorously ‘Test’ any program. However, with very large programs or systems it can be very difficult to test for every possible error and as we don’t want programs to crash during use we need to handle any exceptions to the norm that have not been discovered during the testing process. This can be performed using the Try – Catch exception handler – the basic syntax is shown below:

Try

Dim hyp, perp, base As Single

perp = txtPerpendicular.Text

base = txtBase.Text

hyp = ((perp ^ 2) + (base ^ 2)) ^ 0.5

txtHypotenuse.Text = hyp

Catch ex As Exception

MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, _ MessageBoxIcon.Error)

End Try

The code you want to try is placed in between the Try and Catch keywords and if an error occurs the code will be passed to the Catch clause for evaluation and the error message is displayed.

There are many types of exception which can be viewed when the ‘As’ statement is entered – see below

Each type of error may have its own type of error handler i.e. database type errors, divide by zero exceptions etc. This can be very daunting when you first use the language but the Exception error handler will cope with most errors.

Exercise 2

1.  Try adding a text value to the program after adding the Try-Catch handler – note the error message

2.  Try adding very large numbers to the textboxes – note the error message

3.  Try adding nothing to the textboxes – note the error message

Although the Exception error handler copes with the situations above and prevents the program from crashing, letting the program continue may cause other problems

I suggest that you do not use any error handlers with try and catch until you have rigorously tested your program as you may hide major faults in the logic and performance of your code.

Extension to Exercise 2

Extend your Pythagoras program to include the calculation of the angle that is created at the intersection of the base and hypotenuse i.e.

To accomplish this task you will need the following information:

·  The structure of the calculation is:

Angle = Arc tan (perpendicular / base) * radians

·  Arc tan in VB .Net uses Math.Atan

·  Radians are calculated by using 180/PI

·  PI can be declared as a constant i.e. Const PI = 3.141592654

In a right angled triangle the angle at the intersection of the base and perpendicular sides is always 90 degrees and the total of all three angles is always 180 degrees.

Extend the program further by calculating the angle at the intersection of the perpendicular and hypotenuse i.e.

Modify the Pythagoras interface to display both angles

Summary

In this session we have covered the following topics:

·  Error Types

o  Syntax – errors in the structure of the language

o  Logical – assigning incorrect values or using incorrect formulae etc

o  Runtime – non-syntax errors such as overloading variable types, assigning the wrong values to types etc

·  The Debugger – using the debugger to identify problems in the code at runtime

·  Error Handling – using in-built error handlers to prevent programs from crashing when abnormal conditions occur

Validation of user input will be covered in more detail in later sessions

© Peter Bilbie 2010 Page 12 of 14