Files, Errors, and Automation
26 min read
Try, Except, Else, Finally
Try, Except, Else, Finally
In the last lesson, you learned try and except.
Python also gives two more useful parts:
elsefinally
These help you control what happens after success or error.
Review
try:
# risky code
except:
# run if error happens
What Does else Do?
else runs only if no error happens.
try:
number = int("5")
except:
print("Error")
else:
print("Success")
Output
Success
What Does finally Do?
finally always runs.
It runs:
- after success
- after error
try:
print("Start")
except:
print("Error")
finally:
print("Done")
Output
Start
Done
Full Example
try:
number = int(input("Enter number: "))
except:
print("Invalid input")
else:
print("You entered", number)
finally:
print("Program ended")
Example Output (Good Input)
Enter number: 7
You entered 7
Program ended
Example Output (Bad Input)
Enter number: hello
Invalid input
Program ended
Why Use else?
It keeps success code separate from error code.
Cleaner code.
Why Use finally?
Useful for:
- Closing files
- Cleaning up resources
- Final messages
- Ending tasks safely
File Example
try:
file = open("notes.txt")
text = file.read()
except:
print("File error")
else:
print(text)
finally:
print("Finished")
Output
Finished
(If the file is missing, you still see the final message.)
Code Along
Build a safe divider.
Steps:
- Ask for two numbers
- Divide them
- Show error if needed
- Always print
Done
Mini Challenge
Build a safe login checker.
Steps:
- Ask for age
- Convert to number
- If valid, print age
- If invalid, print error
- Always print
Goodbye
Expected output:
Enter age: hello
Invalid input
Goodbye
Real World Use Case
Programs use finally for cleanup and else for successful actions after risky tasks.
Quiz
- When does
elserun? - When does
finallyrun? - Why is
finallyuseful? - What is the benefit of
else?
Assignment
Create a safe calculator that subtracts two numbers using try, except, else, and finally.
Summary
You learned how else runs after success and finally always runs after try and except.