Vasu Patel logoVasu Patel
← Python Syntax & DSA Reference
All chapters in this track
  1. 011. Variables, Types & Operators
  2. 022. Strings
  3. 033. Lists
  4. 044. Tuples, Sets & Dicts
  5. 055. Control Flow
  6. 066. Error Handling
  7. 077. Functions & Lambdas
  8. 088. Comprehensions
  9. 099. Built-in Functions
  10. 1010. Type Hints (3.10+)
  11. 1111. Classes & Dataclasses
  12. 1212. Iterators & Generators
  13. 1313. DSA Standard Library
  14. 1414. Python 3.9–3.11 Features for DSA
  15. 1515. DSA Idioms & Gotchas
  16. 1616. Master Quick Reference

Chapter 6 of 16

6. Error Handling

Tutorial

The reference tables throughout this doc note "raises KeyError/ValueError if missing" — this is how you actually catch those. Interview solutions rarely need heavy exception handling, but the syntax matters for safe lookups and for LeetCode "Design" problems that manually raise StopIteration (see §12).

# ══ TRY / EXCEPT ════════════════════════════════════════════════
try:
    val = d[key]
except KeyError:
    val = 0                       # equivalent effect to d.get(key, 0)

try:
    x = arr[i]
except IndexError:
    x = None

# Multiple exception types
try:
    n = int(s)
except (ValueError, TypeError):
    n = 0

# ── else / finally ──────────────────────────────────────────────
try:
    result = 10 / divisor
except ZeroDivisionError:
    result = float("inf")
else:
    print("no error occurred")    # runs only if try succeeded
finally:
    print("always runs")          # cleanup, runs no matter what

# ══ RAISE ═══════════════════════════════════════════════════════
def safe_divide(a: int, b: int) -> float:
    if b == 0:
        raise ValueError("division by zero")
    return a / b

# Re-raise with context (debugging chained failures)
try:
    process()
except KeyError as e:
    raise RuntimeError("processing failed") from e

Reference

ExceptionRaised byCommon DSA cause
KeyErrord[missing_key]Use d.get(k, default) instead
IndexErrorarr[out_of_range]Off-by-one in loop bounds
ValueErrorint("abc"), lst.index(missing)Bad input parsing
ZeroDivisionErrorx / 0Guard divisor before dividing
RecursionErrorRecursion too deepSee sys.setrecursionlimit (§15)
StopIterationnext(it) past the endManual iterator protocol (§12)
try/except/else/finally—else runs iff no exception; finally always runs
raise X("msg")—Explicitly signal an error
raise X from e—Chain exception context