Lesson 05
else and finally Blocks — Results and Cleanup in Python
Learn when else runs after successful try execution and why finally is the cleanup block that always executes in Python.
Golden rule:
elseruns only when no exception occurs.finallyruns every time, whether the program succeeds or fails.
What you will learn
- When
elseexecutes - When
finallyexecutes - The complete execution order
- Resource cleanup in real applications
- File and database cleanup patterns
The complete exception flow
This MahiDev diagram shows the exact execution order.
Easy memory formula
| Block | Purpose |
|---|---|
try |
Watch risky code |
except |
Handle errors |
else |
Show successful result |
finally |
Clean up resources |
1. Understanding the else block
The else block is called the Result Generation Block.
It executes only when the try block finishes without any exception.
Visual explanation
Basic syntax
try:
result = 20 / 4
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Division successful:", result)Output:
Division successful: 5.0Notice:
elsenever handles errors. It only runs after successful execution.
2. Why do we need else?
Without else, success code gets mixed with risky code.
Without else (works, but less clear)
try:
result = 20 / 4
print("Result:", result) # success logic inside tryBetter approach
try:
result = 20 / 4
except ZeroDivisionError:
print("Error")
else:
print("Result:", result)Now the responsibilities are separated:
try→ risky workexcept→ error handlingelse→ success result
3. Understanding the finally block
The finally block is called the Resource Relinquishing Block.
It executes 100% of the time.
Think of a library
Whether you finish reading, stop halfway, or encounter an error — you must return the book. That is exactly what finally does.
Visual analogy
4. Interactive division simulator
This shows exactly which blocks execute. Change B to 0 in the playground to trigger an exception.
def divide(a, b):
try:
print("try: computing", a, "/", b)
result = a / b
except ZeroDivisionError:
print("except: zero denominator")
else:
print("else: success — result =", result)
finally:
print("finally: cleanup always runs")
divide(20, 4)
divide(20, 0)finally appears in both successful and failed executions.
5. Complete execution order
Let's trace both possibilities.
Case A — No exception
Output:
try: computing
else: success
finally: cleanupCase B — Exception occurs
Output:
try: computing
except: zero denominator
finally: cleanupNotice:
elsecompletely disappears when an exception is raised.
6. Real-world example — File handling
One of the most common professional uses of finally.
file = None
try:
file = open("marks.txt")
print(file.read())
except FileNotFoundError:
print("File not found")
finally:
if file:
file.close()
print("File closed")In the browser playground, marks.txt may not exist — that is fine. You will see FileNotFoundError handled and finally still run safely because file stays None.
Why use finally?
Even if reading fails:
- File handles are released
- Memory is cleaned
- Resources are not leaked
This is called resource cleanup.
7. Database connection example
Enterprise applications constantly use finally. Here is a simulated pattern (no real database in the playground):
class SimConnection:
def close(self):
print("Connection released")
connection = None
try:
connection = SimConnection()
print("Query executed")
except Exception:
print("Database failed")
finally:
if connection:
connection.close()Resource lifecycle
8. Complete syntax pattern
This is the structure you will use throughout Python.
try:
# risky code
except ValueError:
# handle value errors
except ZeroDivisionError:
# handle division errors
else:
# execute when no exception
finally:
# cleanup alwaysExecution table
| Situation | try | except | else | finally |
|---|---|---|---|---|
| Success | ✅ | ❌ | ✅ | ✅ |
| Exception | ⚠️ Partial | ✅ | ❌ | ✅ |
9. Memory trick
Think of washing dishes.
No matter what happened during cooking, washing dishes always happens. That is finally.
Interview questions
Q1. When does the else block execute?
Answer: Only when the try block completes without raising any exception.
Q2. Does finally execute after an exception?
Answer: Yes. finally always executes whether the program succeeds, fails, returns, or raises an exception.
Q3. What is the main purpose of finally in enterprise applications?
Answer: Releasing resources such as files, database connections, sockets, and locks.
Key takeaways
elseruns only after successful executionfinallyalways executes- Keep success logic in
else, not insidetry - Use
finallyto close files and release database connections - Professional Python applications rely on
finallyfor reliable cleanup - Next: Forms of
exceptBlocks — genericexcept, multiple types, andexcept Exception as err
Loading playground…
Check your understanding
else finally blocks quiz
else block runs when:
1 / 10