Exceptions
Catch ValueError and FileNotFoundError with try and except so a program recovers from bad input, and raise an exception for input a function must refuse.
It opens on
A program asks for your age, and you type twelve in words. Does the program have to crash?
Why it matters
Real programs meet typing mistakes, missing files and impossible values; catching the right exception keeps them running with a helpful message, and raising one makes a function refuse bad input clearly; reading and writing try and except is a standard exam question.
Good to know first
- Debugging: a traceback's last line gives the error type and message
- Input, output and conversion: int turns text into a whole number
- Reading and writing files: with open(name) as f opens a file to read
Step by step
Catching an error
Read the ValueError that int raises on bad text, and catch it with try and except so the function returns a safe value instead.
try runs its block. If a ValueError happens inside it, Python jumps to except ValueError and runs that block instead of crashing.
catching it
A common mix-up
Try makes errors disappear.
In fact: It only catches the types its except names, and the code after the failing line inside try is skipped.
Missing files and several errors
Catch FileNotFoundError when opening a file, and handle different error types with separate except blocks.
Run in a folder with no scores.txt, load printed no such file, scores.txt, and returned the empty string.
A common mix-up
A bare except is the safest choice because it catches everything.
In fact: It also hides bugs like a misspelled name; catch only the errors you expect.
Raising your own
Raise ValueError with a clear message for input a function must refuse, and catch it in a loop that asks again.
set_age(30) returned 30. set_age(−4) raised the error, and the caller caught it and printed caught, age out of range, −4.
A common mix-up
Raise and return do the same thing.
In fact: Return hands back a normal value; raise stops the function with an error that the caller must catch or crash on.
Try it
Write safe_float(text) that returns float(text), or 0.0 when the text is not a number.Answer
Try: return float(text), except ValueError: return 0.0; safe_float("2.5") gives 2.5 and safe_float("abc") gives 0.0
Hint: Float raises ValueError too
In the two-error block, change line 2 to int("7"). What prints?Answer
Ok 5.0, then done
Hint: 10 / 2 is 5.0, and else runs when nothing failed
Write check_percent(p) that raises ValueError if p is outside 0 to 100, else returns p.Answer
If p < 0 or p > 100, raise ValueError with a message; otherwise return p; check_percent(120) raises
Hint: Like set_age
For read_age("twelve"), which lines run, and what is returned?Answer
Lines 2 and 3, where int fails, then the except block on lines 5 and 6, which prints the message and returns None; line 7 never runs.
Which lines print, and in what order?Answer
Divided by zero, then done; the ValueError block is skipped, the ZeroDivisionError block runs, else is skipped since an error happened, and finally always runs.
