Show the difference between the else and finally clauses of a Python try statement.
The else clause runs only when the try block finished without raising an error. The finally clause runs no matter what happened, in every case.
def parse(text):
try:
value = int(text)
except ValueError:
return 'not a number'
else:
return 'number: ' + str(value)
finally:
print('parsed', repr(text))
print(parse('42'))
print(parse('abc'))
Look at the order of the output, because it is the part that confuses people. The line from the finally clause always prints first, because that clause runs while the try statement is still unwinding and before the function actually returns its value. The return in the else clause has already worked out its result by that point.
It is worth being precise about the difference between the two clauses. The else clause covers the success path, which means it holds the code that should only run when the risky operation worked. Putting that code in else rather than at the bottom of the try block means that a failure inside 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 of the function. That is exactly why it is the right place to release a lock, close a connection, or roll something back.