The finally Block
The finally block runs no matter what. It executes whether an error occurs or not. It is typically used for cleanup tasks like closing open files or database connections.
try:
print("Opening database...")
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("Closing database connection... (Always Runs)")
Output:
Opening database...
Cannot divide by zero!
Closing database connection... (Always Runs)
:::tip Golden Rule Never trust user inputs. Always use try-except blocks to protect your programs from crashing due to unexpected input values! :::