0% found this document useful (0 votes)
18 views

Errors and Debugging - Isaac Computer Science

This document discusses different types of errors that can occur when writing code: - Syntax errors occur when the rules of the language are not followed and prevent the code from running. Common causes are missing brackets or semicolons. - Logic errors cause code to work incorrectly but still run, due to issues like incorrect calculations or loops. They are harder to detect than syntax errors. - Semantic errors involve improper code statements and are flagged by compilers, such as using undefined variables or type mismatches. - Common semantic errors include variables of the wrong type or accessing invalid array indexes. Debugging tools help locate errors by showing variable values and traceback information.

Uploaded by

87shf2xx2j
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Errors and Debugging - Isaac Computer Science

This document discusses different types of errors that can occur when writing code: - Syntax errors occur when the rules of the language are not followed and prevent the code from running. Common causes are missing brackets or semicolons. - Logic errors cause code to work incorrectly but still run, due to issues like incorrect calculations or loops. They are harder to detect than syntax errors. - Semantic errors involve improper code statements and are flagged by compilers, such as using undefined variables or type mismatches. - Common semantic errors include variables of the wrong type or accessing invalid array indexes. Debugging tools help locate errors by showing variable values and traceback information.

Uploaded by

87shf2xx2j
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Home Errors and debugging

Errors and debugging

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.

The team's logbook entry with the moth


U.S. Naval History and Heritage Command Photograph NH 96566-KN (Public
domain)

All stages Syntax errors

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

1 user_name = input("Please enter your name: "


2 print(user_name)

View on GitHub

Figure 1: A Python program with a syntax error

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

1 name = input("Please enter your name: ")


2 if name == "Ada"
3 print("Hi Ada, you are one of my heroes!")
4 else:
5 print("Hello ", name)
View on GitHub

Figure 2: A Python program with a syntax error

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#

1 Console.WriteLin("Please enter your name: ");


2 string name = Console.ReadLine();
3 if (name == "Ada") {
4 Console.WriteLine("Hi Ada, you are one of my
5 heroes!");
6 }
7 else {
8 Console.WriteLine("Hello " + name);
}

View on GitHub

Figure 3: A C# program with a syntax error


In Figure 3, the IDE has identified that there is an error on line 9 of the code and has
highlighted that the issue is related to the piece of code WriteLin, which should
actually be written WriteLine.

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.

Common causes of syntax errors


Spelling or typing errors
Missing parentheses, ( ) or { }
Missing colons, :, or semicolons, ;, in statements in which they are required by
the language
Missing or unexpected indentation in Python
Printing a value without declaring it

All stages Logic errors

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#

1 def add_vat (amount):


2 RATE = 20
3 vat = amount * RATE
4 with_vat = amount + vat
5 return with_vat

View on GitHub

1 public static double AddVat(double amount) {


2 // Calculate the vat and add to the amount
3 int RATE = 20;
4 double vat = amount * RATE;
5 double withVat = amount + vat;
6 return withVat;
7 }

View on GitHub
Figure 4: A Python program in which VAT has been calculated by multiplying
the amount by 20, rather than 0.2

Figure 5: A C# 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.

Common causes of logic errors


Not correctly understanding what the program needed to do
Using the incorrect logical operator in a selection statement
Missing or incorrect positioning of brackets in mathematical calculations, which
means that the incorrect result is returned
Loops that execute more or fewer times than intended

A Level Semantic errors

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.

In the Python example below, you will see the statement z = a + x

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)

Figure 6: A traceback as a result of a semantic error

Figure 6, in Python, shows a traceback. It provides useful information to help you


debug the error.

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)

Attempt to add string '2' to integer 3

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])

Figure 7: Attempt to print the contents of a non-existent index

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#

1 number = input("Please enter a number: ")


2 number = int(number)
3 print(number)

View on GitHub

1 Console.WriteLine("Please enter a number:");


2 int number = Int32.Parse(Console.ReadLine());
3 Console.WriteLine(number);

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.

Common causes of runtime errors


Trying to access a list item that does not exist
A mathematical calculation that results in the program trying to divide by 0
Trying to perform numerical operations on strings
Linking to a file or resource that has been moved or no longer exists
A Level Rubber duck debugging

The rubber duck debugging method is as follows:

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.

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.

You might also like