How does exception handling work in Python (try/except/else/finally)?
Reviewed by Gurusankar M.
β‘ Short Answer
Wrap risky code in `try`, handle specific errors in `except`, put code that runs only on success in `else`, and cleanup that always runs in `finally`. Python favors EAFP ('easier to ask forgiveness than permission') β try the operation and catch the specific exception rather than pre-checking everything.
βCoffee Chat Question
Concept Made Simple
βHow does exception handling work in Python (try/except/else/finally)?β
π§ Mind Map Answer
Remember It Faster
β¨οΈHands-on Keyboard
Learn by Doing
def safe_div(a, b):
try:
result = a / b
except ZeroDivisionError:
return "cannot divide by zero"
else:
return result
finally:
print("done")
print(safe_div(10, 2))
print(safe_div(10, 0))done 5.0 done cannot divide by zero
π₯What If?
Think Beyond the Expected
Why is `except Exception:` (or bare `except:`) considered a bad habit?
It swallows every error β including ones you didn't anticipate (typos, KeyboardInterrupt with bare except) β hiding real bugs and making debugging painful. Catch the specific exception you can handle, and let unexpected ones propagate or be logged with context.
πReal World
Robust services catch specific, expected failures (network timeout, missing key, bad input), clean up resources in finally, and let unknown errors bubble up to a logger β never silently pass.
π―Interviewer's Expectation
Keywords they're listening for:
β οΈCommon Mistakes
- βBare `except:` swallowing all errors
- βCatching Exception too broadly
- βUsing exceptions for normal control flow everywhere
β Best Practices
- βCatch the narrowest exception you can handle
- βUse finally / context managers for cleanup
- βLog or re-raise unexpected errors, never silently pass
πFollow-up Questions
- 1EAFP vs LBYL β which does Python prefer?
- 2How do you raise and define custom exceptions?
- 3What does `raise ... from e` do (exception chaining)?
π§©Related Technologies
Continue Learning with AI
Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly β AI is your learning companion, not a shortcut.
Plain-language foundations
I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner. Topic: Exceptions (Python) Interview question: "How does exception handling work in Python (try/except/else/finally)?" Please: 1. Explain the core idea in simple, plain language, using an everyday analogy. 2. Define any technical terms you use. 3. Walk through one small, concrete example. 4. Finish with a single sentence I can easily remember. Keep the tone friendly and assume I'm new to this topic.
Was this answer helpful?
β Featured Products
Support our platform by exploring our recommended products.
As an Amazon affiliate, purchases through these links may earn us a small commission β at no extra cost to you. It helps keep Full Stack Interview Guru free.