finally — Easy Examples
Block that always executes after try/except, used for cleanup
Guaranteed cleanup
Using finally to ensure code always runs.
python
# finally runs no matter what try: print("Trying...") result = 10 / 2 print(f"Result: {result}") finally: print("This ALWAYS runs") print() # finally runs even when exception occurs try: print("Trying...") result = 10 / 0 except ZeroDivisionError: print("Caught error") finally: print("Cleanup done")
Expected Output
Trying... Result: 5.0 This ALWAYS runs Trying... Caught error Cleanup done
finally always executes, whether the try block succeeds, raises an exception, or returns. Use it for cleanup like closing files or releasing locks.
Want to try these examples interactively?
Open Easy Playground