Programming · Robust Code
up to +100 XP
Stop 2.10 · Programming · 3 min

Robust Code

Build reliable and fault-tolerant programs

Learning objectives:
  • Know the characteristics of robust code (2.10.1)
  • Know the debugging process and its role in robust solutions (2.10.2–2.10.3)
  • Locate and correct errors (2.10.4–2.10.5)

Robust code

Robust code keeps working sensibly when things go wrong. It:

while True:
    try:
        quantity = int(input("Quantity: "))
        if quantity > 0:
            break
        print("Enter a number above 0.")
    except ValueError:
        print("Please type a whole number, like 3.")

try and except (in Appendix 2) catch an error so the program can recover.

try:
    file = open("orders.txt", "r")
    data = file.read()
    file.close()
except FileNotFoundError:
    print("No orders saved yet. Starting a new list.")
    data = ""

Debugging

Debugging is the process of locating errors in code and correcting them. Use it whenever code does not do what it should.

Error typeWhat happensExample
Syntax errorBreaks the rules of the language, so the code will not runMissing colon after if
Runtime errorCrashes while runningDividing by zero, int("abc")
Logic errorRuns but gives the wrong resultUsing > instead of >=

How to locate errors

Why debugging makes code robust

Each fixed error is one less way for the program to fail. Testing with unusual and invalid data finds the weak spots so they can be handled before users meet them.

Quick check · 11 questions · up to 100 XP

Check what stuck.

+10 XP each
Question 1

Question 1 of 11

Which is a characteristic of robust code?

Question 2

Question 2 of 11

What should a robust program's error messages be like?

Question 3

Question 3 of 11

What is debugging?

Question 4

Question 4 of 11

Which type of error stops code from running because it breaks the rules of the language?

Question 5

Question 5 of 11

Code runs but outputs the wrong total. What type of error is this?

Question 6

Question 6 of 11

Dividing by zero while a program runs causes…

Question 7

Question 7 of 11

Which Python keywords let a program recover from an error?

Question 8

Question 8 of 11

How does debugging help make a solution robust?

Question 9

Question 9 of 11

Which is a good way to locate an error?

Question 10

Question 10 of 11 · Match the pairs

Match each error type to an example.

Syntax error
Runtime error
Logic error
Question 11

Question 11 of 11 · Coding

Write safe_divide(a, b) that returns a / b, or None if b is 0. Use try and except.

Open the IDE
Hint

Dividing by zero raises ZeroDivisionError.