Menu

Errors in algorithms

Runtime Errors

A runtime error happens while you are running a program. The code has been accepted, so the syntax is fine, and the logic may be correct, but the computer is asked to carry out an operation that cannot be completed. At that moment the program crashes or stops, because the instruction cannot be executed. The important idea is that the operation cannot be completed, not just that an error message appears.

This is different from a syntax error, which stops the program before it runs, and from a logic error, which lets the program finish but gives the wrong result. A runtime error is not simply a program that runs for a long time or repeats forever: a loop that never ends is usually a logic error, because nothing impossible has happened.

Operations that can fail

Some instructions work for many values but fail for a particular one. Common causes include:

  • Division by zero: a calculation such as 15 / 0 has no answer, so Python raises ZeroDivisionError.
  • Accessing an array index outside its bounds: a list with four items has positions 0 to 3, so asking for position 4 raises IndexError.
  • Opening a file that does not exist: Python raises FileNotFoundError.
  • Using data of the wrong type: for example, joining text to a number with + without converting the number with str() raises TypeError.
  • Using a variable before it has been given a value: Python raises NameError.

It may depend on the input

A runtime error can appear only for some inputs or conditions, so a program may pass several tests and still crash later. In the program below, if you choose 0, 1, 2 or 3, the program prints a score. If you choose 4, it asks for an item that does not exist, so the program stops with an IndexError.

scores = [12, 8, 15, 6]
position = int(input("Which score? "))
print("Score: " + str(scores[position]))

Output when the user types 4:

Which score? 4
IndexError: list index out of range (line 3)

Practise this