Python finally Keyword
The finally
block in Python is used in exception handling to define cleanup code that should run no matter what, whether an exception occurred or not.
Why Use finally
?
- It ensures important final steps like closing files, releasing resources, or cleanup tasks are always executed.
- It runs whether:
- An exception occurred
- No exception occurred
- An exception was caught or not
Syntax
try:
# Risky code
except SomeException:
# Handle error
finally:
# Always runs
Example 1: finally
with No Exception
try:
x = 10 / 2
except ZeroDivisionError:
print("Division by zero")
finally:
print("This always runs")
Output:
This always runs
Example 2: finally
with an Exception
try:
x = 10 / 0
except ZeroDivisionError:
print("Caught ZeroDivisionError")
finally:
print("Finally block executed")
Output:
Caught ZeroDivisionError
Finally block executed
Example 3: No except
, Only finally
try:
x = 1 / 0
finally:
print("Cleanup code")
Output:
Cleanup code
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
Explanation:
Even though no except
block is present, the finally
block still runs before the exception is thrown.
Real-World Example: File Handling
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found")
finally:
file.close()
print("File closed")
Bonus: Combine with finally
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input!")
else:
print("Good job! You entered:", num)
finally:
print("Execution complete.")
Summary Table
Block | Runs When |
---|---|
try | When you want to test a block |
except | If an exception occurs in try |
else | If no exception occurs in try |
finally | Always — whether exception or not |