Programming with Python · free preview
Exceptions and Context Managers
Raise your own exceptions, define custom exception classes, run cleanup with finally, and build context managers for setup-and-teardown work.
1. Overview
Overview
2. Raising Exceptions
Raising Exceptions
3. Custom Exception Classes
Custom Exception Classes
4. finally and Cleanup
finally and Cleanup
5. The with Statement's Protocol
The with Statement's Protocol
6. The contextlib Shortcut
The contextlib Shortcut
7. A Validated Loader
A Validated Loader
8. A Timing Context
A Timing Context
9. Order exception cleanup
Inside show, opening prints before an inner try, a custom DataError is caught inside, and an outer finally prints closing. For a bad reading, what is the output order?
10. DataError keeps the original cause and cleanup still runs
Run show on a valid reading and on text that cannot be converted. Predict the opening line, the caught-line contents, the original exception type, and whether the cleanup line appears on both paths.
Example. DataError keeps the original cause and cleanup still runs
Problem. Run show on a valid reading and on text that cannot be converted. Predict the opening line, the caught-line contents, the original exception type, and whether the cleanup line appears on both paths.
Correct solution.
class DataError(Exception):
pass
def load_reading(text):
try:
return float(text)
except ValueError as error:
raise DataError(f"bad reading: {text}") from error
def show(text):
print("opening")
try:
try:
print("reading", load_reading(text))
except DataError as error:
print("caught", error, type(error.__cause__).__name__)
finally:
print("closing")
show("36.6")
show("missing")关键提醒。
Input is two calls: show("36.6") and show("missing").
Trace:
show("36.6")printsopening.load_reading("36.6")converts successfully, so the innerprintshowsreading 36.6.- The outer
finallyprintsclosingbeforeshowreturns to the caller. show("missing")printsopeningagain.float("missing")raisesValueError, theexcept ValueErrorblock raisesDataError(...) from error, and the outerexcept DataErrorcatches that category.error.__cause__is still the originalValueError, so its type name prints.- The outer
finallyprintsclosingeven though the inner block caught the custom error.
Expected output:
Output
opening
reading 36.6
closing
opening
caught bad reading: missing ValueError
closing11. Retrieval practice
A function converts text with float(text) and re-raises failures as ReadingError("bad reading: {text!r}") from error. For input "n/a", state the outer exception type and message, the original exception type under __cause__, and why a surrounding finally still prints cleanup.
def load_reading(text):
try:
return float(text)
except ValueError as error:
raise ReadingError(f"bad reading: {text!r}") from error
load_reading("n/a")12. Mastery check
Write parse_readings(text) that skips a header row, converts each row[1] to float, raises ReadingError("bad reading on row {row_number}") from ValueError, and always prints closing in a finally. Run it on "patient,reading\nAlice,36.6\nBob,bad\n". Give the code, the exact output before the caught message, and the chained cause message.
class ReadingError(Exception):
pass
def parse_readings(text):
# complete the parser
try:
parse_readings("patient,reading\nAlice,36.6\nBob,bad\n")
except ReadingError as error:
print("caught", type(error).__name__, error, type(error.__cause__).__name__, error.__cause__)Practice this interactively
Free account · instant grading · spaced review that schedules itself.
Start this course for free