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'?
IntermediateAnswer
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 aboveReal-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.