Advertisement
Intermediate Python, Exception Handling

How does the 'else' clause on a try statement work, and what's its purpose compared to just putting that code at the end of 'try'?

Short answer

The 'else' clause runs ONLY if the 'try' block completed WITHOUT raising any exception — putting code there (instead of at the end of 'try') makes it explicit that this code is NOT meant to be protected by the except clauses, avoiding accidentally catching exceptions from code…

Save Python mock interview
Advertisement
AModel answer
The 'else' clause runs ONLY if the 'try' block completed WITHOUT raising any exception — putting code there (instead of at the end of 'try') makes it explicit that this code is NOT meant to be protected by the except clauses, avoiding accidentally catching exceptions from code that wasn't the original risky operation.
try:
    value = risky_parse(data)
except ValueError:
    print("Parsing failed")
else:
    print(f"Parsed successfully: {value}")  # only runs if risky_parse succeeded, and its own errors aren't caught above
Real-world example
Clearly separating the 'risky' operation being protected from subsequent code that shouldn't accidentally have its own errors caught by the same except clause.
Likely follow-ups
  • What would go wrong if the 'else' block's code were instead placed at the END of the 'try' block?
Related topics