Exceptions and Defensive Input Handling
Make the word-frequency tool fail well: read files safely, turn input problems into clear messages and exit codes, and let real bugs surface.
Contentsand lesson path
On this page
- The problem
- Step 1: read the traceback
- Step 2: name the errors the user can fix
- Step 3: know what else and finally do
- Step 4: validate numbers at the boundary
- Step 5: handle errors at the edge
- Check your understanding
- Apply it
- Review prompt
Lessons of Python Foundations
- Values, Control Flow, Functions and Classes Concept · 25 min
- Choosing Lists, Dicts, Sets, Tuples and Dataclasses Worked example · 20 min
- Exceptions and Defensive Input Handling Worked example · 15 min
- Modules, Packages and Virtual Environments Lab · 25 min
- Type Hints and Tests with pytest Lab · 25 min
- Check: Read, Fix and Test a Script Knowledge check · 6 questions
What you will learn
- Write functions that use core data structures (lists, dicts, sets, tuples) and handle errors with exceptions.
01. The problem
The word-frequency tool takes two inputs from a person: a file path and a --top number. People mistype paths, point tools at PDFs and type --top ten, and at the moment each of those ends in a traceback that looks like a crash. As in lesson 1, the commands below use python3; on Windows, type py instead.
This walk-through draws a clear line. Problems with the input, which the user can fix, get a one-line message and a non-zero exit code that scripts can detect. Unexpected problems, which usually mean a bug in your code, still produce a full traceback, because that is the information you need to fix them.
02. Step 1: read the traceback
Start from the simplest possible loader and give it a path that does not exist.
import sys
from pathlib import Path
def load_text(path: Path) -> str:
with open(path, encoding="utf-8") as file:
return file.read()
print(len(load_text(Path(sys.argv[1]))))python3 read_demo.py missing.txtTraceback (most recent call last):
File ".../read_demo.py", line 10, in <module>
print(len(load_text(Path(sys.argv[1]))))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File ".../read_demo.py", line 6, in load_text
with open(path, encoding="utf-8") as file:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'Read a traceback from the bottom up. The last line names the exception type and its message; the frames above it show the chain of calls, most recent last. Here open() raised FileNotFoundError inside load_text().
Two details of the loader are worth keeping. The with statement closes the file when its block ends, even if an exception escapes. And the encoding is explicit because, before Python 3.15, the default depends on the operating system and its settings; naming it keeps the code correct on every version.
03. Step 2: name the errors the user can fix
Decide which failures the user can fix: a missing file and a file that is not UTF-8 text both qualify. Give them one exception type of your own, so the rest of the program can handle them together. A custom exception subclasses Exception; this one keeps the path and reason as attributes and passes the message to the parent with super().__init__().
class InputError(Exception):
"""Bad input the user can fix; the CLI reports it without a traceback."""
def __init__(self, path: Path, reason: str) -> None:
super().__init__(f"{path}: {reason}")
self.path = path
self.reason = reason
def load_text(path: Path) -> str:
"""Read a UTF-8 text file; raise InputError for problems the user can fix."""
try:
with open(path, encoding="utf-8") as file:
return file.read()
except FileNotFoundError as err:
raise InputError(path, "file not found") from err
except UnicodeDecodeError as err:
raise InputError(path, "not UTF-8 text") from errEach except clause names one failure you understand. Anything else, such as a permission problem or a bug in your own code, still reaches the user as a traceback until you decide it deserves a friendlier message.
raise ... from err attaches the original exception as the cause of the new one, so if an InputError ever goes unhandled, the traceback shows both and no detail is lost.
Such a chained traceback has two parts. Python prints the original exception first, here the FileNotFoundError with the open() line that failed, then the line "The above exception was the direct cause of the following exception:", then the InputError and the raise line that created it. Read it from the bottom: the last line is the error that stopped the program, and the part above the separator tells you where the trouble started. If the separator says "During handling of the above exception, another exception occurred:" instead, the second exception was raised inside an except block without from. That is either a handler that forgot from err, or a bug in the handler itself, so read its line before you trust the message.
Why not check path.exists() first? The file can disappear between the check and open(), and exists() says nothing about permissions or encoding, so you would still need the try. Python style is to attempt the operation and handle the specific failure.
04. Step 3: know what else and finally do
A try statement can have two more clauses. else runs only when the try block raised nothing, which keeps the success path outside the try so its own errors are not caught by mistake. finally runs on every path, handled error or not, which makes it the place for clean-up when with is not available.
def parse_confidence(raw: str) -> float | None:
try:
score = float(raw)
except ValueError:
print(f"skipped {raw!r}: not a number")
return None
else:
print(f"parsed {score}")
return score
finally:
print("checked", repr(raw))
parse_confidence("0.82")
parse_confidence("n/a")parsed 0.82
checked '0.82'
skipped 'n/a': not a number
checked 'n/a'finally runs even though both of the other branches have already reached a return.
05. Step 4: validate numbers at the boundary
--top arrives as a string. argparse accepts any function as an argument's type: it calls the function with the raw string and, if the function raises ValueError or argparse.ArgumentTypeError, prints a usage message and exits with status 2.
import argparse
def positive_int(value: str) -> int:
"""argparse type for --top: a whole number of at least 1."""
number = int(value) # int("ten") raises ValueError
if number < 1:
raise argparse.ArgumentTypeError(f"must be at least 1, got {number}")
return numberThe core should still check the number, so top_words() raises ValueError when n < 1. Validating at the boundary gives the user a helpful message; validating in the core protects every other caller, including your tests.
06. Step 5: handle errors at the edge
Catch InputError in exactly one place: the main() function that talks to the terminal. It prints the message to standard error and returns an exit code, which sys.exit(main()) hands to the shell. The functions below main() never print or exit, which keeps them easy to test. Add import sys to the imports at the top of wordfreq.py.
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
prog="wordfreq", description="Print the most frequent words in a text file."
)
parser.add_argument("path", type=Path, help="UTF-8 text file to read")
parser.add_argument("--top", type=positive_int, default=10, help="words to show")
args = parser.parse_args(argv)
try:
text = load_text(args.path)
except InputError as err:
print(f"wordfreq: error: {err}", file=sys.stderr)
return 1
for record in top_words(count_words(tokenize(text)), args.top):
print(record)
return 0
if __name__ == "__main__":
sys.exit(main())The if __name__ == "__main__": guard runs main() only when the file is executed as a script, not when a test imports it. Save the three ticket lines from the previous lesson as tickets.txt and try one good run and two bad ones. $? holds the last exit code in bash and zsh; PowerShell uses $LASTEXITCODE.
python3 wordfreq.py tickets.txt --top 3
python3 wordfreq.py missing.txt; echo "exit code $?"
python3 wordfreq.py tickets.txt --top ten; echo "exit code $?"WordCount(word='refund', count=3)
WordCount(word='invoice', count=2)
WordCount(word='amount', count=1)
wordfreq: error: missing.txt: file not found
exit code 1
usage: wordfreq [-h] [--top TOP] path
wordfreq: error: argument --top: invalid positive_int value: 'ten'
exit code 207. Check your understanding
def read_budget(raw: str) -> int:
try:
budget = int(raw)
except ValueError:
print("A")
budget = 0
else:
print("B")
finally:
print("C")
return budget
print(read_budget("1k"))08. Apply it
Bring your wordfreq.py up to this standard:
- Add
InputError, the newload_text(),positive_int()andmain(), and maketop_words()raiseValueErrorwhenn < 1. - Run the tool on
tickets.txt, on a missing file and with--top 0, and check the message and exit code each time. - Copy any PNG image to
bad.txtand confirm that you getnot UTF-8 textrather than a traceback.
Stretch: point the tool at a folder. If that deserves a friendly message, add an except clause for the specific error you see; Linux and macOS raise a different exception type from Windows.
09. Review prompt
Without looking back:
- In which order do you read a traceback, and what does each part tell you?
- What separates an error the user can fix from a bug, and how should the tool report each?
- When does an
elseclause run, and when doesfinallyrun? - Why does
main()return an exit code instead of printing and carrying on, and why does it write errors to standard error?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.