There's more to error handling than catching
The problem...
You know try / except. You catch the error. You handle it. Done.
But sometimes you need more. Code that runs only when everything worked. Code that runs no matter what — success or failure.
try / except alone can't do that cleanly.
The idea!
Two more blocks complete the picture. else runs when the try succeeded — no errors. finally runs always — whether the try succeeded or failed.
The full syntax
try:
# code that might fail
except ErrorType:
# runs if try failed
else:
# runs if try succeeded — no errors
finally:
# always runs — success or failure
else — when everything worked
try:
age = int(input("Enter your age: "))
except ValueError:
print("Numbers only, please.")
else:
print(f"Your age is {age}.") # only runs if no error
If int() succeeds — else runs. If it fails — except runs, else is skipped. Cleaner than putting the success code inside try.
finally — always runs
try:
age = int(input("Enter your age: "))
except ValueError:
print("Numbers only, please.")
finally:
print("Thank you for using this program.")
Valid input or not — finally always executes. Use it for cleanup code that must run regardless.
All four together
def get_age():
try:
age = int(input("Enter your age: "))
except ValueError:
print("Numbers only, please.")
return None
else:
print(f"Valid age received: {age}.")
return age
finally:
print("Input attempt complete.")
result = get_age()
print(result)
# Valid input:
# Enter your age: 25
# Valid age received: 25.
# Input attempt complete.
# 25
# Invalid input:
# Enter your age: abc
# Numbers only, please.
# Input attempt complete.
# None
finally runs in both cases. else only runs when there's no error.
Heads up!
else— runs only whentrysucceeded, skipped ifexceptranfinally— always runs, no exceptions- You don't need all four — use only what you need
finallyruns even if there's areturninsidetryorexcept
The mindset shift
Stop thinking: "I just need to catch the error."
Start thinking: "What runs on success? What always runs? Plan for both."
What you should understand now
else— runs whentrysucceeds, skipped whenexceptrunsfinally— always runs, regardless of success or failure- Use
elsefor success logic — usefinallyfor cleanup - You don't need all four blocks — use only what the situation requires