In Python error handling, we have seen how
try and except work together.
But sometimes, we want to run extra code whether or not an error happens.
This is where else and finally come in.
πΉ The else Block
The else block runs only if no error occurs in the try block.
try:
number = int(input("Enter a number: "))
except ValueError:
print("That's not a number!")
else:
print("Great! You entered:", number)
π If the user enters 10, output will be:
Great! You entered: 10
π If the user enters hello, output will be:
That's not a number!
πΉ The finally Block
The finally block runs no matter what happens — whether an error occurs or not.
It is often used for cleanup actions like closing files or releasing resources.
try:
f = open("data.txt", "r")
content = f.read()
except FileNotFoundError:
print("File not found!")
finally:
print("Closing file (if it was opened).")
π If data.txt exists, the file will be read and then closed.
π If data.txt does not exist, you still see:
File not found!
Closing file (if it was opened).
πΉ Syntax of try–except–else–finally
try:
# Code that might raise an error
except SomeError:
# Handle the error
else:
# Runs if no error happens
finally:
# Always runs (cleanup code)
⚠️ Common Mistakes
- Using capitalized
ElseorFinally→ must be lowercase. - Forgetting that
finallyruns always, even if there is an error. - Using
finallywithout cleanup logic — defeats its main purpose.
No comments:
Post a Comment