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.

python
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:

  1. show("36.6") prints opening.
  2. load_reading("36.6") converts successfully, so the inner print shows reading 36.6.
  3. The outer finally prints closing before show returns to the caller.
  4. show("missing") prints opening again.
  5. float("missing") raises ValueError, the except ValueError block raises DataError(...) from error, and the outer except DataError catches that category.
  6. error.__cause__ is still the original ValueError, so its type name prints.
  7. The outer finally prints closing even though the inner block caught the custom error.

Expected output:

Output

opening
reading 36.6
closing
opening
caught bad reading: missing ValueError
closing

11. 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.

python
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.

python
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