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:
- handles unexpected inputs: rejects or asks again for bad data instead of crashing
- handles unexpected terminations: deals with problems such as a missing file without the whole program failing
- produces specific and meaningful error messages: tells the user what went wrong and what to do.
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 type | What happens | Example |
|---|---|---|
| Syntax error | Breaks the rules of the language, so the code will not run | Missing colon after if |
| Runtime error | Crashes while running | Dividing by zero, int("abc") |
| Logic error | Runs but gives the wrong result | Using > instead of >= |
How to locate errors
- Read the error message and line number.
- Trace the code by hand with test values.
- Add
print()statements to see values as the code runs. - Use the IDE's debugging tools to step through line by line.
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.