Python · Fundamentals & Gotchas

What is exception handling?

Mediumexceptionstryexceptfinallyraise

Interview question

What is exception handling in Python?

How to answer

The short answer

Exception handling is how you detect and recover from runtime errors using try / except / else / finally, instead of crashing the process.

  • try: code that might fail
  • except: handlers for specific exception types (prefer narrow types)
  • else: runs if try had no exception
  • finally: always runs (cleanup)
  • raise: throw / rethrow an exception
Python
def parse_int(raw: str) -> int:
    try:
        value = int(raw)
    except ValueError as exc:
        raise ValueError(f"not an int: {raw!r}") from exc
    else:
        return value
    finally:
        print("attempt finished")

try:
    print(parse_int("42"))
    print(parse_int("x"))
except ValueError as exc:
    print("handled:", exc)

# Catch multiple
try:
    ...
except (KeyError, IndexError) as exc:
    ...

# Bare except / except Exception: use sparingly; can hide bugs

Best practices

  • Catch the narrowest exception you can handle.
  • Use raise ... from exc to preserve chains.
  • Prefer for resource cleanup over only finally blocks when both apply.
  • Do not use exceptions for ordinary control flow in hot paths.

Lock it in with a real drill

You remember an answer longer once you have used it. Try a hands-on problem on this concept.

Open related drill