Skip to main content
MahiDev — Learn. Build. Become AI-ready.

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.

Intermediate35 min
else finally blocks hero Module 15 Lesson 5 MahiDev

Golden rule: else runs only when no exception occurs. finally runs every time, whether the program succeeds or fails.

What you will learn

  • When else executes
  • When finally executes
  • 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.

Complete exception flow try except else finally 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

Success path else runs failure path else skipped MahiDev

Basic syntax

python
try:
    result = 20 / 4

except ZeroDivisionError:
    print("Cannot divide by zero")

else:
    print("Division successful:", result)

Output:

text
Division successful: 5.0

Notice: else never 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)

python
try:
    result = 20 / 4
    print("Result:", result)  # success logic inside try

Better approach

python
try:
    result = 20 / 4

except ZeroDivisionError:
    print("Error")

else:
    print("Result:", result)
Separate try except else responsibilities MahiDev

Now the responsibilities are separated:

  • try → risky work
  • except → error handling
  • else → 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

MahiDev library analogy borrow read return book finally

Whether you finish reading, stop halfway, or encounter an error — you must return the book. That is exactly what finally does.

Visual analogy

Open database read write finally close connection always

4. Interactive division simulator

This shows exactly which blocks execute. Change B to 0 in the playground to trigger an exception.

Division simulator success else finally vs except skip else
python
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

Success flow try no exception else finally

Output:

text
try: computing
else: success
finally: cleanup

Case B — Exception occurs

Exception flow try ZeroDivisionError except skip else finally

Output:

text
try: computing
except: zero denominator
finally: cleanup

Notice: else completely disappears when an exception is raised.


6. Real-world example — File handling

One of the most common professional uses of finally.

File handling try except FileNotFoundError finally close MahiDev
python
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):

python
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

Database Connect Use Close finally guarantees close

8. Complete syntax pattern

This is the structure you will use throughout Python.

python
try:
    # risky code

except ValueError:
    # handle value errors

except ZeroDivisionError:
    # handle division errors

else:
    # execute when no exception

finally:
    # cleanup always

Execution table

Situation try except else finally
Success ✅ ❌ ✅ ✅
Exception ⚠️ Partial ✅ ❌ ✅

9. Memory trick

Think of washing dishes.

MahiDev memory story try cook except burn else serve finally wash 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

  • else runs only after successful execution
  • finally always executes
  • Keep success logic in else, not inside try
  • Use finally to close files and release database connections
  • Professional Python applications rely on finally for reliable cleanup
  • Next: Forms of except Blocks — generic except, multiple types, and except Exception as err

Loading playground…

Check your understanding

else finally blocks quiz

else block runs when:

1 / 10