Reading preferences
Concept

Exception Flow and Context Managers

Trace successful and exceptional paths while ensuring cleanup.

python, exceptions, try, context managers, cleanup

Trace both outcomes

An exception interrupts normal control flow. Catch only failures you can handle; otherwise let them reach a caller that can report them. else runs when the try suite finishes normally, and finally runs during normal exit and exception propagation.

Python illustration

class InvalidCount(ValueError):
    pass

def read_count(text):
    value = int(text)
    if value < 0:
        raise InvalidCount("count must not be negative")
    return value

try:
    count = read_count("-2")
except InvalidCount as error:
    print(f"Invalid count: {error}")
else:
    print(f"Count: {count}")
finally:
    print("Check finished")

Prepared output — not live execution:

Invalid count: count must not be negative
Check finished

int can also raise ValueError for text that is not an integer. This handler catches only the custom subclass, so that different error propagates.

See the reasoning

Follow the example one step at a time

Compare the invalid and valid paths through try, except, else, and finally. This is a prepared teaching demonstration, not live code execution.

Invalid input

read_count("-2") → int("-2") → -2

Conversion succeeds, but the count is negative.

Context managers

with open("notes.txt", encoding="utf-8") as file: enters a file context and closes the file on exit, including when its body raises an exception. The context manager's __enter__ supplies the value after as; __exit__ receives exception details and may suppress an exception by returning a truthy value. File objects do not normally suppress errors.

For a small custom context manager, contextlib supplies a decorator:

from contextlib import contextmanager

@contextmanager
def named_session(name):
    print(f"Enter {name}")
    try:
        yield name
    finally:
        print(f"Leave {name}")

with named_session("study") as session:
    print(session)

The prepared output is Enter study, study, and Leave study, on separate lines. The finally block also runs if the body raises, and this example does not suppress the exception.

Avoid return in finally: it can replace a pending return or suppress an exception. Prefer narrow try blocks, specific exception types, and useful messages. Never treat a failed operation as if it succeeded.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. When does a try statement's else block run?
2. What is finally normally used for?
3. Why define a custom exception?
4. What does a context manager provide?

References and further reading