Python foundations

Python try and except: Catch and Handle Exceptions

Catch a specific Python exception, keep success code in else, clean up with finally, and preserve the original cause with raise from.

Put an operation that may fail inside try and handle the expected failure with a specific except clause. For example, wrap int(raw) in a handler for ValueError when text may contain an invalid number. Keep unrelated code outside the try block so its errors are easier to diagnose.

def parse_seat_count(raw):
    try:
        count = int(raw)
    except ValueError as exc:
        raise ValueError("Seat count must be a whole number") from exc

    if count < 1:
        raise ValueError("Seat count must be positive")
    return count

assert parse_seat_count("12") == 12

parse_seat_count("four") reports that a whole number is required. parse_seat_count("0") succeeds at conversion, then reports that the count must be positive. The raise ... from exc form preserves the original conversion exception in the traceback. For help reading it, see how to read a Python error.

Catch only the failures that imply the same action

except ValueError handles that class and its subclasses. If both ValueError and a documented TypeError require the same response at your boundary, a tuple can list both alternatives: except (ValueError, TypeError):. That choice depends on who owns the bad input. A malformed form value can be reported to the user. An accidental wrong type passed by your own code may be an error you want to see while testing.

A broad except Exception can belong at an application boundary that records failures and returns a controlled status. It usually conceals too much inside a small conversion function. A bare except also catches exceptions outside the ordinary Exception hierarchy, including user interrupts. Give a failure an action that fits its meaning instead of turning every exception into a successful empty result.

When the try/except else block runs

The optional else runs when the try block finishes without raising an exception or leaving early through return, break, or continue. Put the next step in else when its errors should pass through to the caller instead of being handled by the preceding except clauses.

messages = []
for raw in ("3", "bad", "5"):
    try:
        number = int(raw)
    except ValueError:
        messages.append("Invalid record")
    else:
        messages.append(f"Parsed {number}")

assert messages == ["Parsed 3", "Invalid record", "Parsed 5"]

For a small application, keeping a short protected expression and returning or raising from its handler often reads clearly without an else. The important point is that subsequent operations are outside a handler that cannot respond to their errors correctly.

Clean up with a context manager or finally

A finally block runs when control leaves the protected operation, including many paths that raise an exception. It is useful for cleanup that is independent of the outcome. A context manager such as with open(...) as handle already provides cleanup for that resource, so a separate finally is unnecessary for the ordinary file handle case.

Avoid returning a normal result from cleanup code. A return from finally can override an earlier return and suppress a pending exception. Cleanup can itself fail, so design it with a clear idea of what resources were successfully acquired and which operation owns each one.

Check callers see the right failure

Test valid input, the intended exception, and the expected state afterward. For example, a file import that rejects an invalid row should leave no unintended partial update if its caller expects an all-or-nothing operation. For a tool that deliberately keeps valid rows, report the rejected count and preserve enough context to find the problem.

A useful error message identifies the failed operation and the correction a person can make. Include the underlying exception in appropriate diagnostics when a maintainer needs it. Avoid echoing sensitive input when a field name, line number, or synthetic example would be enough to diagnose the issue.

Sources and further reading

Related reading

Browse Python foundations · Explore project tutorials

Search PythonProjects.org