All chapters in this track
- 011. Variables, Types & Operators
- 022. Strings
- 033. Lists
- 044. Tuples, Sets & Dicts
- 055. Control Flow
- 066. Error Handling
- 077. Functions & Lambdas
- 088. Comprehensions
- 099. Built-in Functions
- 1010. Type Hints (3.10+)
- 1111. Classes & Dataclasses
- 1212. Iterators & Generators
- 1313. DSA Standard Library
- 1414. Python 3.9–3.11 Features for DSA
- 1515. DSA Idioms & Gotchas
- 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
| Exception | Raised by | Common DSA cause |
|---|---|---|
KeyError | d[missing_key] | Use d.get(k, default) instead |
IndexError | arr[out_of_range] | Off-by-one in loop bounds |
ValueError | int("abc"), lst.index(missing) | Bad input parsing |
ZeroDivisionError | x / 0 | Guard divisor before dividing |
RecursionError | Recursion too deep | See sys.setrecursionlimit (§15) |
StopIteration | next(it) past the end | Manual 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 |