EasyπŸ‘€ 0-2 yearsπŸ‘€ 3-5 years 1 min read

How does exception handling work in Python (try/except/else/finally)?

Reviewed by Gurusankar M.

Asked inInfosysTCSAccentureAmazon
#exception#try except#finally#eafp#error handling
Report issue

⚑ 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

try→code that might fail
except X→handle a specific error
else→runs only if no exception
finally→always runs (cleanup)

⌨️Hands-on Keyboard

Learn by Doing

python
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))
Output
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:

βœ“ try/except/else/finally rolesβœ“ catch specific exceptionsβœ“ EAFP styleβœ“ finally for cleanupβœ“ avoid bare except

⚠️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

custom exceptionscontext managerslogging

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?

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.

Related Questions