Error Handling and Debugging
22 min read
Finally
Finally
Sometimes you need code to run no matter what happens.
For example:
- Close a file
- Show a final message
- Clean up resources
- End a task safely
Python gives us finally for this.
What Is finally?
finally is a block that always runs.
It runs:
- if the code succeeds
- if an error happens
Basic Structure
try:
# risky code
except:
# handle error
finally:
# always runs
Example: Final Message
try:
print("Start")
except:
print("Error")
finally:
print("Done")
Output
Start
Done
Example: Bad Input
try:
number = int(input("Enter number: "))
print(number)
except:
print("Invalid input")
finally:
print("Program ended")
Output Example
Enter number: hello
Invalid input
Program ended
Example: File Cleanup
file = None
try:
file = open("notes.txt")
print(file.read())
except:
print("File error")
finally:
if file:
file.close()
print("Finished")
Why Use finally?
Use it when something must happen at the end.
Examples:
- Close files
- Disconnect tools
- Save logs
- Final message
finally with No Error
try:
print(10 / 2)
except:
print("Error")
finally:
print("Always runs")
Output
5.0
Always runs
Code Along
Build a safe greeter.
Steps:
- Ask for name
- Print greeting
- Always print
Goodbye
Mini Challenge
Build a safe divider.
Steps:
- Ask for two numbers
- Divide them
- Handle errors
- Always print:
Done
Expected output:
Enter first number: 5
Enter second number: 0
Error
Done
Real World Use Case
Programs use finally for cleanup, closing files, ending sessions, and final system actions.
Quiz
- When does
finallyrun? - Does it run after an error?
- Why is
finallyuseful? - Name one real use of
finally.
Assignment
Create a program that asks for a number and prints it. Handle bad input and always print Finished.
Summary
You learned that finally always runs and is useful for cleanup and final actions.