Errors and exceptions
Course contents (15 lessons)
- Getting started
- Installing Python 3.13 and running your first script
- Variables and basic data types
- Text, numbers and user input
- Working with strings
- Numbers and arithmetic
- Input and output: talking to the user
- Making decisions and repeating work
- Making decisions with if, elif and else
- Loops: for, while, break and continue
- Collections of data
- Lists and tuples
- Dictionaries and sets
- Functions and modules
- Writing your own functions
- Modules, pip and virtual environments
- Files and errors
- Reading and writing files
- Errors and exceptions
- Final project: expense tracker
- Project: build the expense tracker, part 1
- Project: summaries, search and improvements
Programs fail. That is normal.
A user types "abc" where you expected a number. A file is missing. A network call times out. When something goes wrong, Python raises an exception. If nobody handles it, the program stops and prints a traceback.
Reading a traceback
Traceback (most recent call last):
File "calc.py", line 5, in <module>
result = total / count
ZeroDivisionError: division by zero
Read it from the bottom. The last line names the exception type and message. Above it is the line that failed. If the error happened inside a function, you will see several lines, one per call, with the most recent last. People often panic at long tracebacks, but the answer is nearly always in the last two lines.
Catching exceptions
Use try and except to deal with an error you expect.
import json
from pathlib import Path
def read_int(prompt):
"""Keep asking until the user types a whole number."""
while True:
text = input(prompt)
try:
return int(text)
except ValueError:
print(f"'{text}' is not a whole number. Try again.")
def load_tasks(path):
try:
with open(path, encoding="utf-8") as f:
data = json.load(f)
except FileNotFoundError:
print("No saved tasks yet, starting fresh.")
return []
except json.JSONDecodeError:
print("The file is damaged, starting fresh.")
return []
else:
print(f"Loaded {len(data)} tasks.")
return data
finally:
print("Finished reading.")
count = read_int("How many tasks do you want to add? ")
tasks = load_tasks(Path("tasks.json"))
print(count, tasks)
How try, except, else and finally fit together
Python runs the try block. If an exception happens, it looks for an except clause that matches the type and runs it. If nothing went wrong, the else block runs. The finally block runs no matter what, even after a return. It is the place for cleanup.
In read_int, the loop repeats until int() succeeds. That is the standard recipe for validating input, and you will use it many times.
Common exception types
| Exception | Typical cause |
|---|---|
ValueError | Right type, bad value: int("abc") |
TypeError | Wrong type: "a" + 1 |
KeyError | Missing dictionary key |
IndexError | List position out of range |
FileNotFoundError | File does not exist |
ZeroDivisionError | Dividing by zero |
NameError | Using a variable that was never defined, often a typo |
Catch narrowly
The worst habit in error handling is the bare except:
try:
risky()
except: # catches everything, even Ctrl+C
pass # and hides the problem
This silences real bugs. You make a typo, the code fails, and you never find out why. Always name the exception you expect, such as except ValueError:. If you want a catch-all for logging, use except Exception as error:, print or log the error, and consider raising it again with a bare raise.
Getting the error object
Use as to see the message:
try:
price = float("12,50")
except ValueError as error:
print("Could not read the price:", error)
Raising your own errors
When your function gets input that makes no sense, raise an exception instead of returning a strange value.
def apply_discount(price, percent):
if not 0 <= percent <= 100:
raise ValueError("percent must be between 0 and 100")
return price * (1 - percent / 100)
try:
apply_discount(500, 150)
except ValueError as error:
print("Error:", error)
This is better than returning -1 or None, because a caller cannot ignore an exception by accident.
Do not use try for everything
Sometimes a simple check is clearer. If you only want to avoid dividing by zero, if count == 0: is simpler than catching ZeroDivisionError. Use exceptions for things outside your control, like files, networks and user input.
Try it yourself
Write a function safe_divide(a, b) that returns the result, or prints a friendly message and returns None when b is zero. Then write a loop that asks the user for a price until they type a valid positive number, rejecting text and negative values with different messages. Hint: raise a ValueError for the negative case inside the try block.
import json
from pathlib import Path
def read_int(prompt):
"""Keep asking until the user types a whole number."""
while True:
text = input(prompt)
try:
return int(text)
except ValueError:
print(f"'{text}' is not a whole number. Try again.")
def load_tasks(path):
try:
with open(path, encoding="utf-8") as f:
data = json.load(f)
except FileNotFoundError:
print("No saved tasks yet, starting fresh.")
return []
except json.JSONDecodeError:
print("The file is damaged, starting fresh.")
return []
else:
print(f"Loaded {len(data)} tasks.")
return data
finally:
print("Finished reading.")
count = read_int("How many tasks do you want to add? ")
tasks = load_tasks(Path("tasks.json"))
print(count, tasks)
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account