How do try, except, else and finally work together in Python?
try holds the risky code, except handles an error, else runs only if no exception occurred, and finally always runs, whether or not there was an error. Use else for code that depends on the try succeeding.
Explain it simply
Think of a UPI payment. You try to pay. If it fails, you handle the failure (except). If it succeeds, you show the success slip (else). Either way, you close the payment screen (finally).
Example
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("cannot divide by zero")
return None
else:
print("division worked")
return result
finally:
print("done")
print(divide(10, 2))
# Output: division worked
# Output: done
# Output: 5.0
print(divide(1, 0))
# Output: cannot divide by zero
# Output: done
# Output: NoneNotice that finally printed before the return value was shown, even though return was already reached. It runs on the way out.
What to say in the interview
"try is the risky block, except catches specific exceptions, else runs only when nothing was raised, and finally always runs, so it's the place for cleanup like closing files. I keep the try block small and put the follow-up code in else, so an error there isn't accidentally caught by my except."
Common mistakes
- Putting a lot of unrelated code in
try, which hides real bugs.