Show the difference between the else and finally clauses of a Python try statement.
The else clause runs only when the try block succeeded. The finally clause runs no matter what happened.
def parse(text):
try:
value = int(text)
except ValueError:
return "not a number"
else:
return f"number: {value}"
finally:
print(f"parsed {text!r}")
print(parse("42")) # parsed '42' then number: 42
print(parse("abc")) # parsed 'abc' then not a numberLook at the order of the output. The finally line always prints first, because the finally clause runs as the try statement is unwinding, before the function actually returns its value. The return in the else clause has already computed its result by then.
The distinction is worth being precise about. The else clause covers the success path — the code that should only run when the risky operation worked. Putting it there, rather than at the bottom of the try block, means a failure in the try block cannot accidentally skip it.
The finally clause is the cleanup path. It runs whether the try block succeeded, whether an except clause handled the error, or whether the exception is still on its way out. That makes it the right place for releasing a lock, closing a connection or rolling something back.