Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python exceptions reference: raise, propagate, chain and clean up

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

Exception handling chooses which failures to translate or handle while finally provides cleanup during normal return or stack unwinding.

Download Python source kit

Operation contract

The bounded parser translates an integer-conversion ValueError into a domain ValueError with an explicit cause. A finally suite appends a cleanup marker regardless of acceptance or rejection. The caller catches only the declared domain failure. Two calls show cleanup on both paths without a finally return that would hide the rejected input.

Failure and ownership boundary

Exception messages can reveal received values if they are copied into logs; this fixture reports a fixed domain message. Bare except and broad BaseException handling can interfere with process control. Resource acquisition itself may fail before a finally-managed body starts, which is why Python ExitStack: unwind partially acquired resources has its own pattern. Python ExceptionGroup: handle selected failures and retain the rest needs except* rather than flattening all failures.

Working program

python
cleanup = []
def parsed_quantity(text):
    try:
        try:
            return int(text)
        except ValueError as cause:
            raise ValueError("quantity conversion rejected") from cause
    finally:
        cleanup.append("released")

print(parsed_quantity("3"))
try:
    parsed_quantity("invalid")
except ValueError as failure:
    print(str(failure))
    print("cause retained:", failure.__cause__ is not None)
print(cleanup)

Output

Output
3
quantity conversion rejected
cause retained: True
['released', 'released']

Costs and limits

The fixture has fixed small input. Int conversion can accept more syntax than a field grammar and allocate larger integers for longer text; see the strict parser rather than treating this reference operation as complete wire validation.

Common Mistakes

  • Cleanup should not replace the pending exception with a return.
  • Catch the intended failure category and keep received secrets out of messages.

Connected lessons

Python type conversion: parsing success is not field validity, Python exception interview: chained causes and a finally return that hides failure, Python ExitStack: unwind partially acquired resources.

python
exceptions-reference
Storage details