The else clause of a try statement runs when the try body finishes without an exception, before finally.
Python interview: try else runs only after the try body succeeds
Operation contract
The parser logs a successful integer conversion in else and cleanup in finally. A malformed field skips else, enters the ValueError handler and still executes finally. This ordering matters when a writer records success: putting that record in finally would mark a failed parse as accepted. The event list makes both traces testable without inspecting traceback text.
Failure and ownership boundary
The catch is limited to ValueError from integer conversion. A broader catch could hide a bug unrelated to the field. No data is committed by this fixture; Python sqlite3 transactions: bind values and roll back failed batches must still define when parsed data becomes visible. Python interview: a return from finally replaces a pending exception is a different finally hazard.
Working program
def parse_amount(text):
events = []
try:
amount = int(text)
except ValueError:
events.append("rejected")
amount = None
else:
events.append("parsed")
finally:
events.append("cleanup")
return amount, events
print(parse_amount("125"))
print(parse_amount("bad"))Output
(125, ['parsed', 'cleanup'])
(None, ['rejected', 'cleanup'])Costs and limits
Conversion cost depends on input length and integer digits, so a real boundary needs length and magnitude caps before accepting user text. The event list stores two short strings per call in this fixture.
Common Mistakes
- else is skipped when the try body raises.
- finally is for cleanup, not unconditional success recording.
Connected lessons
Python exceptions: translate an input error without hiding its cause, Python interview: a return from finally replaces a pending exception, Python sqlite3 transactions: bind values and roll back failed batches.
