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

Python interview: try else runs only after the try body succeeds

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

The else clause of a try statement runs when the try body finishes without an exception, before finally.

Download Python source kit

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

python
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

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.

python
try-else-finally-interview
Storage details