An exception interrupts normal execution and carries failure information to a caller that can handle that boundary.
Python exceptions: translate an input error without hiding its cause
Operation contract
The receipt parser catches only the ValueError raised by integer conversion, then raises a domain error with explicit chaining. Negative amounts fail a separate business rule. The caller distinguishes parsing rejection from successful conversion instead of catching every Exception and manufacturing a zero amount.
Failure and ownership boundary
A broad catch can conceal programming errors such as a missing attribute. Finally also runs during failure, so returning from finally can suppress an exception the caller needed to see. Keep cleanup in Python context managers: clean up on success and failure and keep error messages bounded rather than echoing an entire sensitive import record.
Working program
def parse_minor_amount(text):
try:
amount = int(text)
except ValueError as cause:
raise ValueError("integer amount required") from cause
if amount <= 0:
raise ValueError("positive amount required")
return amount
print(parse_minor_amount("125"))
try:
parse_minor_amount("12x")
except ValueError as failure:
print(str(failure))
print(type(failure.__cause__).__name__)Output
125
integer amount required
ValueErrorCosts and limits
Conversion cost grows with input length and retained integer digits. This fixture uses tiny strings; an external request must cap length before converting.
Common Mistakes
- Catch the failure you can handle.
- Do not return from finally to hide a pending error.
Connected lessons
Python context managers: clean up on success and failure, Python input exercise: accept an explicit integer grammar, Java exceptions: recovery boundaries and failure context.
Follow the related contract
Python ExceptionGroup: handle selected failures and retain the rest, Python exceptions reference: raise, propagate, chain and clean up, Python exception interview: chained causes and a finally return that hides failure.
Follow the service contract
Python assert versus input validation: optimized execution changes the contract.
Check this related boundary
Python interview: a return from finally replaces a pending exception.
Trace the related workflow
Python interview: try else runs only after the try body succeeds.
