How does exception handling work in Python (try/except/else/finally)?
⚡ 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.