Errors and Debugging - Isaac Computer Science
Errors and Debugging - Isaac Computer Science
You will often encounter errors when you write code. Every programmer, even the most
experienced programmers, will need to resolve errors and debug their code. It is all part of
the programming process.
Debugging is the process of finding and correcting existing and potential errors (also
called bugs) in software code. Bugs can cause software code to behave unexpectedly or
crash.
The term 'bug' is sometimes attributed to Grace Hopper. She was a mathematician and a
pioneer of computer programming who joined the United States Naval Reserve and
worked at Harvard University during the Second World War. In 1947, when a computer
she was working on at Harvard was malfunctioning, her team found a bug — an actual
insect — in the machine. They taped the bug into their logbook, writing "First actual case
of bug being found". This incident helped popularise the term 'bug' within the computer
science industry. The team's logbook, complete with the bug, is held at the National
Museum of American History in Washington, D.C.
When you first get started with coding, you will probably make lots of syntax errors.
These are errors that occur when you have not followed the rules of the language,
and they will be flagged by the translator. A program with syntax errors will not run.
Most IDEs (integrated development environments) highlight syntax errors when you
try to run your code. Below is some Python code that contains a syntax error.
Python
View on GitHub
The IDE in Figure 1 has helpfully drawn attention to the error and displayed a
message to explain that the bracket was never closed. If you press 'OK', it leaves the
cursor at the point where the error was thrown (where the program identified the
error), so that the problem can be quickly identified. Different IDEs offer different
levels of feedback and help when syntax errors occur. To find out more about the
different types of IDE, visit the IDEs topic.
Below is another Python program, this time with a different syntax error.
Python
In Figure 2, a different IDE has been used. It has identified the syntax error, but also
has an 'Assistant' window on the right-hand side, which is giving the user more
information about the error. Notice that the error message also tells you what line of
code the error has occurred on; this is particularly useful when finding and identifying
errors in large sections of code.
Below is the same code, this time written in C#, with a different syntax error.
C#
View on GitHub
As you become more experienced, you will probably be able to recognise and
correct syntax errors quickly. However, if you make syntax errors frequently, you may
find it helpful to use an IDE with autocomplete features, such as automatically
closing brackets and automatic indentation.
Logic errors are errors that cause a program to work incorrectly or unexpectedly.
With a logic error, the program can be run without failing, but it does not return the
expected result.
Logic errors are typically more difficult to detect and find than syntax errors, as the
IDE will not be able to pick up the issues or produce clear error messages.
Consider the following program and look at the output that it produces when the
function is called in Python, Figure 4, or in C#, Figure 5.
Python C#
View on GitHub
View on GitHub
Figure 4: A Python program in which VAT has been calculated by multiplying
the amount by 20, rather than 0.2
VAT is a consumption tax that is applied to the purchase of goods or services. The
standard rate of VAT is 20% (in the UK), so the constant should be assigned a value
of 0.2 (or 20/100) in order to calculate the amount of VAT correctly.
With this particular example, a user would hopefully be able to spot that the result is
incorrect, but this is not always the case. Therefore, it is very important that you test
every program you write.
Debugging logic errors often involves tracking the values of variables, as code is
executed step by step. Many IDEs offer a 'Watch' window that allows you to specify
one or more variables to watch. Dry running, which is where the programmer goes
through the code line by line using a trace table, is a manual approach to the same
task.
Semantic errors occur where there is improper use of a program code statement,
and they are flagged by the translator.
and they are flagged by the translator.
This statement has correct syntax, but you are not allowed to use an undefined
variable when adding two values.
Python
1 def create_error():
2 x = 2 * 23
3 z = a + x
4 print (z)
Notice that it starts by stating: most recent call last. This means that you will
probably find the most useful part of the traceback at the end. In this instance, on the
final line of the traceback, it clearly states: name 'a' is not defined. Moving up
through the traceback, you can see on the previous line that the error occurred on
line 4 of the function create_error in the file semantic_error.py. It can be very
helpful to start at the end of the traceback and step back through it, if you have long
chains of procedure calls.
There are two semantic errors that you will frequently encounter. The first is a type
mismatch, which occurs when the operation is not allowed for the type(s) of data
being used For example, if you tried to add a string variable to a number type
variable.
Python
1 def type_mismatch():
2 '''force a type mismatch'''
3 a = 3
4 b = '2'
5 print (a + b)
Another very common error is index out of range, which occurs if you attempt to
access a position in an array or list that does not exist.
Python
1 def out_of_range():
2 '''force index out of range error'''
3 array = [1,2,3,4,5,6]
4 print (array[10])
In the Python example above, there is a list with six elements. An attempt has been
made to access the tenth element and you can see the result in Figure 7. With just
two lines of code, this is fairly easy to debug and fix. However, in most instances the
index will be a variable that has been calculated elsewhere, which means that it may
require a lot more work to track down the source of the error.
All stages Runtime errors
Runtime errors occur when the program is run, as the name suggests. They are
sometimes also referred to as execution errors. These errors occur when the code
is valid according to rules of syntax and semantics (ensuring that a compiler can
understand the source code), and is also logically correct, but the environment that
the program is being run in or the input provided causes an error to occur.
You may have encountered runtime errors when writing programs. Below is a
program that asks the user to input a number.
Python C#
View on GitHub
View on GitHub
This is a perfectly functional program if the user types in an integer value, such as
"8". However, if the user types in something like "eight" or "8.0", this will result in a
runtime error (in Python this specific error is called a ValueError, or in C# an
ArgumentException) because the program does not know how to convert the input
into an integer.
These types of runtime errors can occur because the user has made a mistake or
misinterpreted what they need to input, or potentially because of malicious input.
Whatever the cause, programmers should be able to anticipate this situation
occurring. Programming languages provide a way to handle such errors (usually
known as exceptions). Exception handling is a method for reducing the occurrence
of runtime errors.
Next, consider the following example. A game program provides a way to see users'
high scores, and it stores that information in a file named 'highscores.txt'. To read the
scores from the file, the code might look like this:
Python C#
1 with open("highscores.txt", "r") as file_object:
2 lines = file_object.readlines()
3 print(lines)
View on GitHub
1 string lines;
2 using (StreamReader reader = new
3 StreamReader("highscores.txt")) {
4 lines = reader.ReadToEnd();
5 }
Console.WriteLine(lines);
View on GitHub
This code contains no syntax or semantic errors. However, the code can potentially
result in a runtime error because it is reliant on the existence of the 'highscores.txt'
file. If this file does not exist in the folder at the time the code is run — the code
might have been moved to a different folder or the file may have been deleted
accidentally — then a runtime error will occur.
1. Obtain a rubber duck (the sort you might use in the bath).
2. Place the rubber duck next to your computer and tell it that you need some
help.
3. Explain to the duck what your code is supposed to do; give an overview and
then explain your code slowly and carefully, line by line. You must speak out
loud — the duck needs to hear your explanation.
4. At some point you will realise that what you are telling the duck that your code
does, is not what it is actually doing. Or, that what it is doing is not what it is
supposed to do. Now you can fix the problem!
5. Thank the duck sincerely for its help.
This sounds an unlikely approach to debugging, but it often works. How many times
have you asked your teacher for help, only to realise that you know what the problem
is as soon as you start to explain?
The science behind rubber duck debugging is that, in being forced to explain things
line by line, you challenge everything that you are taking for granted. You have a
view of how your code works. However, you also know that there is something
wrong. In explaining what you think you are doing, slowly and carefully, you will
realise that you are not actually doing what you say you are doing.
All teaching materials on this site are available under the Open
Government Licence v3.0, except where otherwise stated.