By the end of this lesson
Read the last exception line and catch an expected conversion failure.
Before you start
- Python 3.12 or a compatible newer Python 3 interpreter; no external packages.
- Complete lesson 12 in this route, or be comfortable with its examples.
Three words to know
- Exception
- An error condition that interrupts normal execution.
- Traceback
- A report of the call path leading to an exception.
- Handler
- An except block for an expected error.
1. Read the message, then the location
A traceback ends with the exception type and message. Use the file and line information above it to find the operation. SyntaxError means the source could not be parsed; ValueError and TypeError often occur after execution starts. Do not paste error output back into a source file.
def parse_count(text):
try:
return int(text)
except ValueError:
return None
print(parse_count("12"))
print(parse_count("twelve"))
What you should see · example output
12 None
2. Catch narrowly
The example returns None as a documented failure result; callers must check for it. In a larger program you may instead raise a ValueError with a clear message. Avoid except: pass: it hides the evidence needed to repair the problem. Catch expected errors around the operation that can cause them, rather than wrapping unrelated code in one broad handler.
3. Reject before producing output
If a report needs complete input validation, build and validate its data first and write the report only afterward. Otherwise a later error can leave a partial result that looks successful. The final project writes errors to stderr with a nonzero exit status so scripts can distinguish a failure from valid data.
YOUR TURN
A small check before you continue
What is wrong with replacing every exception with an empty list?
Show a suggested answer
It makes missing files, invalid input and programming mistakes look like a legitimate empty result. Handle expected cases explicitly and preserve a useful failure signal.
Sources and scope
Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.
