← Lesson
BitWithBite
Python · Quick Reference

Lesson 14 — Exception Handling Cheat Sheet

Python
In one line: An exception is a signal that something went wrong at runtime. When Python hits an error it cannot handle (dividing by zero, missing file, wrong type), it raises an exception ob...

Key Ideas

1What Are Exceptions?. An exception is a signal that something went wrong at runtime. When Python hits an error it cannot handle (dividing by zero, missing file, wrong type), it raises an ex...
2try / except / else / finally. The full try block has four clauses. You don't need all of them every time — but understanding each one is essential for writing production-quality code.
3Raising Exceptions & Custom Exceptions. You can raise exceptions yourself with the raise keyword — when input is invalid, a business rule is violated, or a state is impossible. Creating custom exception clas...
4Context Managers & __enter__ / __exit__. The with statement you've been using for files is powered by the context manager protocol. Any class implementing __enter__ and __exit__ can be used with with. __exit_...

Code Examples

# ── Basic try/except ────────────────────────── def safe_divide(a, b): try: result = a / b except ZeroDivisionError: return None else: return result # only reached if no exception print(safe_divide(10, 2)) # 5.0 pri...
# ── Raising built-in exceptions ─────────────── def set_age(age): if not isinstance(age, int): raise TypeError(f"Age must be int, got {type(age).__name__}") if age 0 or age > 150: raise ValueError(f"Age {age} is out of valid rang...
import time class Timer: """Context manager that times a code block.""" def __enter__(self): self.start = time.perf_counter() return self # bound to 'as t' def __exit__(self, exc_type, exc_val, exc_tb): self.elapsed ...