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
elseBlock: Code for the "Happy Path." - The
finallyBlock: 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?
- Readability: Distinguishes between "Error Handling" (
except) and "Success Logic" (else). - Reliability:
finallyensures that your computer doesn't run out of memory or leave files locked if a crash happens.
Practice Exercise: The Calculation Log
- Write a script that asks for two numbers to divide.
- In the
tryblock, perform the division. - In the
exceptblock, handleZeroDivisionError. - In the
elseblock, print the result. - In the
finallyblock, print"Calculation attempt finished."
Quick Knowledge Check
- When does the
elseblock run? - What is the main purpose of the
finallyblock? - If a function
returns inside atryblock, does thefinallyblock still run? (Hint: Yes!) - Why is it helpful to use
elseinstead of putting success logic inside thetryblock?
Key Takeaways
elseruns on success.finallyruns regardless of errors or successes.finallyis the safest place for resource cleanup.- Using the full
try-except-else-finallyloop 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!