Functions and ErrorsLesson 15 of 1915 min
Errors and Exceptions
Read a traceback, catch the failures worth catching, and raise your own.
By the end you will be able to
- Read a traceback from the bottom up
- Handle specific exceptions with try/except
- Use else and finally, and raise your own errors
Read the last line first
When Python cannot continue it prints a traceback. The bottom line names the error type and message — read that first, then walk up to find the line in your code that triggered it.
Common types worth recognising:
| Error | Usually means |
|---|---|
SyntaxError | A typo — a missing colon, bracket, or quote |
NameError | Used a variable that does not exist (often a misspelling) |
TypeError | Wrong type — e.g. "3" + 1 |
ValueError | Right type, impossible value — e.g. int("abc") |
IndexError | List index past the end |
KeyError | Dict key does not exist |
ZeroDivisionError | Divided by zero |
try / except
Wrap the risky operation in try. If it raises, the matching except block runs instead of the program crashing.
42
None
5.0
inf
None
— expected output; press Run to execute it yourselfelse and finally
elseruns only if thetryblock raised nothingfinallyruns either way — the place for cleanup that must not be skipped
parsed 10
(finally always runs)
'ten' is not a number
(finally always runs)
— expected output; press Run to execute it yourselfRaising your own
Use raise to reject input your function cannot sensibly handle. Failing loudly and immediately beats returning a nonsense value that corrupts something three steps later.
30
ValueError: age cannot be negative, got -5
TypeError: age must be an integer
— expected output; press Run to execute it yourselfExercise
Write safe_average(numbers) that returns the mean of a list, but returns 0 for an empty list instead of raising ZeroDivisionError.
Press Run to execute this code.