else and finally in Exception Handling
else in try/except
elseelse runs only if no exception occurred.
try_else.py
try:
x = int("42")
except ValueError:
print("Invalid number")
else:
print("Parsed successfully:", x)try_else.py
try:
x = int("42")
except ValueError:
print("Invalid number")
else:
print("Parsed successfully:", x)finally in try/except
finallyfinally runs always (success or error). This is useful for cleanup.
try_finally.py
f = None
try:
f = open("data.txt", "r")
print(f.read())
except FileNotFoundError:
print("File not found")
finally:
if f is not None:
f.close()
print("File closed")try_finally.py
f = None
try:
f = open("data.txt", "r")
print(f.read())
except FileNotFoundError:
print("File not found")
finally:
if f is not None:
f.close()
print("File closed")Prefer context managers when possible
Instead of manual .close().close(), use withwith.
with_open.py
try:
with open("data.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("File not found")with_open.py
try:
with open("data.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("File not found")When is finally important?
- closing files
- releasing locks
- closing DB connections
- cleaning up temporary files
๐งช Try It Yourself
Exercise 1 โ The else Clause
Exercise 2 โ The finally Clause
Exercise 3 โ else + finally Together
If this helped you, consider buying me a coffee โ
Buy me a coffeeWas this page helpful?
Let us know how we did
