Back to results for “Exception Handling”
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'?

Intermediate

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.

Common follow-ups: What would go wrong if the 'else' block's code were instead placed at the END of the 'try' block?