Module 5 Lesson 9: Finally and Else Blocks
·Programming

Module 5 Lesson 9: Finally and Else Blocks

The complete error handling loop. Learn how to use 'else' for success and 'finally' for guaranteed cleanup, ensuring your program leaves no loose ends.

Module 5 Lesson 9: Finally and Else Blocks

You’ve mastered try and except. But what if you have code that should only run if the try block succeeded? Or code that must run whether it crashed or not? Python provides the else and finally keywords to handle these exact scenarios.

Lesson Overview

In this lesson, we will cover:

  • The else Block: Code for the "Happy Path."
  • The finally Block: The "Guaranteed Cleanup" code.
  • The Full Cycle: Combining all four keywords.
  • Practical Example: A robust database simulation.

1. The else Block: Success Only

The else block runs only if the try block did NOT throw an error. This is better than putting everything inside the try because it keeps the try block small and focused only on the part that might fail.

try:
    num = int(input("Enter a number: "))
except ValueError:
    print("That wasn't a number!")
else:
    print(f"Success! The square of your number is {num ** 2}")

2. The finally Block: No Matter What

The finally block runs every single time, regardless of whether an error happened or was caught. This is where you put your "Cleanup" code (like closing files or database connections).

try:
    file = open("data.txt", "r")
    # ... process file ...
except FileNotFoundError:
    print("File not found.")
finally:
    print("Cleaning up resources...")
    # This runs even if FileNotFoundError happened!

3. The Full Pattern

Here is how all four work together in harmony:

try:
    # 1. Code that might fail
    print("Opening connection...")
except:
    # 2. Runs ONLY if code fails
    print("Handling error...")
else:
    # 3. Runs ONLY if code succeeds
    print("Success! Doing work...")
finally:
    # 4. Runs NO MATTER WHAT
    print("Closing connection.")

4. Why Use Them?

  1. Readability: Distinguishes between "Error Handling" (except) and "Success Logic" (else).
  2. Reliability: finally ensures that your computer doesn't run out of memory or leave files locked if a crash happens.

Practice Exercise: The Calculation Log

  1. Write a script that asks for two numbers to divide.
  2. In the try block, perform the division.
  3. In the except block, handle ZeroDivisionError.
  4. In the else block, print the result.
  5. In the finally block, print "Calculation attempt finished."

Quick Knowledge Check

  1. When does the else block run?
  2. What is the main purpose of the finally block?
  3. If a function returns inside a try block, does the finally block still run? (Hint: Yes!)
  4. Why is it helpful to use else instead of putting success logic inside the try block?

Key Takeaways

  • else runs on success.
  • finally runs regardless of errors or successes.
  • finally is the safest place for resource cleanup.
  • Using the full try-except-else-finally loop makes your code extremely robust.

What’s Next?

We know how to handle errors. But how do we keep track of them over time so we can fix them later? In our final lesson of this module, Lesson 10, we’ll learn Logging and Debugging Files!

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn