Skip to content

Lesson 22 of 52Pythonic Python

Errors and Exceptions

Catch, raise and design exceptions so failures are handled where they should be and never silently lost.

28 min read0/7 questions

You can now model your own data with classes. This unit covers the habits that make code read as Python, and it starts with what happens when things go wrong. Real programs fail all the time: files go missing, networks time out, users type "twelve" into a number field. What separates a production service from a script is how it handles those failures. Good error handling means the right code deals with the right problem, and nothing ever fails silently. Interviewers notice instantly when a candidate writes a bare except:.

What an exception is

When Python hits a problem it cannot continue past, it raises an exception: an object describing what went wrong. The exception travels up the call stack, function by function, until some code catches it. If nothing does, the program stops and prints a traceback: the chain of calls that led to the error, most recent call last.

Python
def parse_age(text): return int(text) def register(form): age = parse_age(form["age"]) return f"registered, age {age}" try: print(register({"age": "36"})) print(register({"age": "thirty"}))except ValueError as e: print("caught:", type(e).__name__, "-", e)
Output
Press Run (⌘ Enter) to see what happens.

int("thirty") raised ValueError deep inside parse_age. It flew up through register and was caught at the top. The functions in between did not need any error handling code at all.

try, except, else, finally

The full statement has four parts. Only try plus at least one except or finally is required.

Python
def read_number(text): try: n = int(text) # code that might fail except ValueError: print(f" {text!r} is not a number") return None else: print(f" parsed {n}") # runs only if try succeeded return n finally: print(" done") # ALWAYS runs, even after return for t in ["42", "4x2"]: print(t) read_number(t)
Output
Press Run (⌘ Enter) to see what happens.
  • except handles a specific error type. You can have several, checked top to bottom, and catch more than one type with a tuple: except (KeyError, IndexError):.
  • else runs only when no exception happened. It keeps the try block small, so you do not accidentally catch errors from code you did not mean to guard.
  • finally runs no matter what: success, exception, return or break. It is for cleanup like closing connections (though with usually does that better).
Put it in order4 steps

A try block succeeds and contains a return. In what order do the parts run?

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Predict the outputPython

What does this print?

def f():
  try:
      return "try"
  finally:
      print("cleanup")

print(f())
Need a nudge? Hints walk you through it.

The exception hierarchy

Exceptions are classes, organised by inheritance. except X also catches every subclass of X. That is why order matters: put specific handlers before general ones.

Part of Python's built-in exception tree
BaseExceptiondo not catch thisSystemExitsys.exit()KeyboardInterruptCtrl+CValueErrorright type, bad valueTypeErrorwrong typeKeyErrormissing dict keyIndexErrorlist index out of rangeLookupErrorZeroDivisionErrorArithmeticErrorFileNotFoundErrorTimeoutErrorOSErrorI/O, also called IOErrorExceptioncatch this or belowroot

Almost every error you will handle inherits from Exception. Your own exceptions should too.

1/3
Quick check
What prints?
try:
  {}["missing"]
except LookupError:
  print("lookup")
except KeyError:
  print("key")
Need a nudge? A hint rules out a wrong answer.

Raising exceptions and making your own

Use raise to signal that your function cannot do its job. Pick the built-in type that fits (ValueError for a bad value, TypeError for a wrong type), or define your own by subclassing Exception. Custom exceptions let callers catch exactly your errors, and can carry extra data.

Python
class PaymentError(Exception): """Base class for all payment failures in this app.""" class InsufficientFunds(PaymentError): def __init__(self, balance, amount): super().__init__(f"need {amount}, have {balance}") self.balance = balance self.amount = amount def withdraw(balance, amount): if amount <= 0: raise ValueError("amount must be positive") if amount > balance: raise InsufficientFunds(balance, amount) return balance - amount try: withdraw(50, 80)except InsufficientFunds as e: print("declined:", e, "| short by", e.amount - e.balance)except PaymentError: print("some other payment problem")
Output
Press Run (⌘ Enter) to see what happens.

A small hierarchy (one base class for your app or library, specific subclasses below it) lets callers choose: catch InsufficientFunds to show a nice message, or PaymentError to handle everything from this module.

Inside an except block, a bare raise re-raises the current exception unchanged. Use it when you want to log something and let the error continue upwards.

Chaining: raise ... from

Often you catch a low-level error and raise a more meaningful one. Use raise NewError(...) from original so the traceback shows both: what happened and why. The original is stored on the new exception as __cause__.

Python
import json class ConfigError(Exception): pass def load_config(text): try: return json.loads(text) except json.JSONDecodeError as e: raise ConfigError("config file is not valid JSON") from e try: load_config("{bad json")except ConfigError as e: print(e) print("caused by:", type(e.__cause__).__name__)
Output
Press Run (⌘ Enter) to see what happens.

Python 3.11 added exception groups for code that can fail in several ways at once, such as many concurrent tasks. ExceptionGroup bundles several exceptions, and except* handles each type inside it. You will mostly meet them through asyncio.TaskGroup.

try:
    raise ExceptionGroup("batch failed", [ValueError("bad row"), KeyError("id")])
except* ValueError as group:
    print("value errors:", group.exceptions)
except* KeyError as group:
    print("key errors:", group.exceptions)

Exception groups in practice

Ordinary exceptions assume one thing went wrong. Some code genuinely has several failures at once: an asyncio.TaskGroup where three of ten tasks crashed, a form validator that found four bad fields, a batch job where some rows failed. Reporting only the first throws the rest away. An ExceptionGroup carries all of them, and except* lets each handler take the part it understands.

Python
def validate(row): problems = [] if not row.get("email"): problems.append(ValueError("email is required")) if row.get("age", 0) < 0: problems.append(ValueError("age must be positive")) if "id" not in row: problems.append(KeyError("id")) if problems: raise ExceptionGroup(f"row {row} is invalid", problems) try: validate({"email": "", "age": -1})except* ValueError as eg: for e in eg.exceptions: print("value:", e)except* KeyError as eg: print("missing keys:", [e.args[0] for e in eg.exceptions]) # Only part of the group handled: the rest is re-raised as a smaller grouptry: try: validate({"id": 7, "email": "", "age": -1}) except* KeyError: print("never runs: this row has an id")except ExceptionGroup as rest: print("left over:", rest.exceptions) # A plain exception caught with except* arrives wrapped in a grouptry: raise TimeoutError("db")except* TimeoutError as eg: print(type(eg).__name__, eg.exceptions) # split() does the same partitioning by handeg = ExceptionGroup("batch", [ValueError(1), KeyError(2), ValueError(3)])values, others = eg.split(ValueError)print(len(values.exceptions), len(others.exceptions))
Output
Press Run (⌘ Enter) to see what happens.

The rules that differ from plain except:

  • Every matching clause runs, once, with a sub-group of the matching exceptions. With plain except only the first match runs.
  • Anything unmatched is re-raised automatically as a smaller group. You cannot accidentally swallow an error type you did not name.
  • The variable is always a group, even when a single bare exception was raised. Loop over eg.exceptions.
  • You cannot mix except and except* in one try, and you cannot use return, break or continue inside an except* block. Each is a SyntaxError.
  • Plain except ExceptionGroup still works if you want the whole group at once, and eg.split(Type) or eg.subgroup(Type) partition a group by hand, for example to log each failure.

Where you will meet them at work: asyncio.TaskGroup (Async and Await) raises an ExceptionGroup when tasks fail, and it cancels the remaining tasks first. Code that calls a TaskGroup needs except* around it, or an except ExceptionGroup that inspects the contents. Do not reach for groups in your own APIs just because they exist: if callers only ever need the first failure, a normal exception is simpler for everybody.

Adding context with add_note

raise ... from changes the exception type: callers now catch your ConfigError instead of a JSONDecodeError. Sometimes you want the opposite. You want the same exception to keep flowing, so existing handlers still match, but with an extra clue for whoever reads the traceback. Since 3.11 every exception has add_note():

Python
import traceback def import_rows(rows): total = 0 for line_no, row in enumerate(rows, start=1): try: total += int(row["amount"]) except (KeyError, ValueError) as e: e.add_note(f"while importing line {line_no}: {row!r}") raise return total try: import_rows([{"amount": "10"}, {"amount": "12.5"}])except ValueError as e: print("type kept:", type(e).__name__) print("notes:", e.__notes__) print("--- the traceback ends with:") print("".join(traceback.format_exception(e)[-2:]), end="")
Output
Press Run (⌘ Enter) to see what happens.

Notes are stored in e.__notes__ and printed under the error message in the traceback, and logging's logger.exception(...) (The logging Module) includes them too. The rule of thumb: use from when you translate an error into your own type at a boundary; use add_note when you only add context on the way up. Typical notes are a line number in an import, the attempt number in a retry, or the id of the record being processed. Keep them free of secrets and personal data, because tracebacks end up in log systems that many people can read.

Quick check
A CSV import fails with ValueError on one row, and callers already handle ValueError. You want the traceback to show the row number. What is the best change?
Need a nudge? A hint rules out a wrong answer.

EAFP vs LBYL

There are two styles for dealing with things that might not work:

  • LBYL, "look before you leap": check first. if key in d: value = d[key].
  • EAFP, "easier to ask forgiveness than permission": just try, and handle the failure. try: value = d[key] except KeyError: ....

Python culture leans towards EAFP. It avoids doing the check twice, and it avoids race conditions: between os.path.exists(path) and open(path), another process could delete the file. Trying and catching is the only version that is always correct.

if os.path.exists(path):
    with open(path) as f:      # file may vanish in between
        data = f.read()
else:
    data = ""

Exceptions and performance

Is try slow? Since Python 3.11, entering a try block costs essentially nothing: CPython uses "zero-cost" exception handling, where the handler locations live in a side table that is only consulted when something is actually raised. Raising and catching is the expensive part. Python has to create the exception object, build the traceback and search for a handler.

Python
import timeit d = {"a": 1} def eafp_hit(): try: return d["a"] except KeyError: return 0 def eafp_miss(): try: return d["zzz"] except KeyError: return 0 def lbyl_miss(): return d["zzz"] if "zzz" in d else 0 def get_miss(): return d.get("zzz", 0) n = 200_000base = timeit.timeit(eafp_hit, number=n)for f in (eafp_hit, eafp_miss, lbyl_miss, get_miss): t = timeit.timeit(f, number=n) print(f"{f.__name__:10} {t / base:5.1f}x")
Output
Press Run (⌘ Enter) to see what happens.

Exact numbers vary by machine and Python version (the browser is slower again), but the shape is stable: a try that succeeds is as fast as no try, and a try that fails is several times slower than a check. That gives a practical rule. EAFP when failure is rare (the file usually exists, the key is usually there), a check or .get() when failure is normal (half the lookups miss). And never use exceptions as ordinary control flow in a hot loop. Profiling and Making Python Fast shows how to find out whether any of this matters for your code; usually it does not.

Never swallow errors

The worst error handling is the kind that hides errors:

try:
    charge_customer(order)
except:            # catches EVERYTHING, even Ctrl+C and typos (NameError)
    pass           # and then pretends nothing happened

The customer is not charged, nobody knows, and a typo in charge_customer looks identical to a declined card. The rules:

  1. Catch the narrowest exception you can actually handle.
  2. Never use bare except:. If you truly need a catch-all at the top of a program, use except Exception and log it with the traceback.
  3. Keep the try block as small as possible.
  4. If you cannot do anything useful about an error, let it propagate.
Quick check
Which handler is the best choice for parsing a user-typed quantity?
Need a nudge? A hint rules out a wrong answer.

Designing an exception hierarchy

The small PaymentError tree above is the start of a design every library and service needs. Look at how requests, SQLAlchemy or httpx do it and you see the same shape:

An exception hierarchy for a billing package
BillingErrorone base: catch everything from this packageInvalidAmountValidationErrorcaller's fault, do not retryCustomerNotFoundNotFoundalso a LookupErrorCardDeclinedcarries card_id, reasonPaymentFailedthe provider said noProviderTimeoutProviderUnavailabletransient, safe to retryroot

One base class per package. A caller who just wants 'anything from billing' writes one except BillingError, and never has to know your internals.

1/4

The design rules that go with it:

  1. Wrap third-party errors at your boundary. If your billing package lets an httpx.ConnectTimeout escape, every caller now depends on httpx, and switching HTTP client breaks them. Catch it inside and raise ProviderTimeout(...) from e. The original stays in the traceback.
  2. Catch broadly only at the edges. except Exception belongs in a few places: the web framework's error handler, a worker loop that must survive one bad job, main() of a CLI. There you log the full traceback and turn the error into a 500 response, a failed job or an exit code. Everywhere else, catch the specific errors you can handle.
  3. Map to the outside world in one place. Route handlers should not each translate CustomerNotFound into a 404. Register one handler that maps your hierarchy to HTTP status codes (FastAPI's exception_handler does this).
  4. Do not invent types nobody catches. Each class should exist because some caller handles it differently. Twenty classes that are always caught as the base are noise.

One trap senior engineers know: exceptions get pickled when they cross a process boundary (multiprocessing, concurrent.futures.ProcessPoolExecutor, Celery). Pickling rebuilds an exception by calling the class with self.args. If your __init__ takes two arguments but passes a single formatted message to super().__init__, the rebuild fails, and instead of your error the parent process gets a confusing TypeError.

Python
import pickle class BillingError(Exception): """Base for everything this package raises.""" class CardDeclined(BillingError): def __init__(self, card_id, reason): super().__init__(card_id, reason) # keep ALL args in self.args self.card_id = card_id self.reason = reason def __str__(self): return f"card {self.card_id} declined: {self.reason}" class CustomerNotFound(BillingError, LookupError): """Also a LookupError, so generic 'not found' handlers still work.""" class BadDeclined(BillingError): def __init__(self, card_id, reason): super().__init__(f"card {card_id} declined: {reason}") # one arg only self.card_id = card_id for exc in (CardDeclined("c_42", "insufficient funds"), BadDeclined("c_42", "expired")): try: copy = pickle.loads(pickle.dumps(exc)) print("round trip ok:", copy, "| card:", copy.card_id) except TypeError as e: print(type(exc).__name__, "cannot be unpickled:", e) try: raise CustomerNotFound("cus_9")except LookupError as e: print("caught as LookupError:", type(e).__name__, isinstance(e, BillingError))
Output
Press Run (⌘ Enter) to see what happens.

Pass every constructor argument to super().__init__ and build the readable message in __str__. (The earlier InsufficientFunds example has exactly the BadDeclined bug, which is fine in one process and breaks the day someone moves the work to a process pool.)

Quick check
Your service calls a payment provider through httpx. Where should httpx.ConnectTimeout be handled?
Need a nudge? A hint rules out a wrong answer.

Warnings: problems that are not errors yet

Not every problem should stop the program. When you rename a parameter in a shared library, you want old callers to keep working and to hear about it. The warnings module is for that.

Python
import warnings def fetch_users(limit=None, page_size=None): if limit is not None: warnings.warn( "fetch_users(limit=...) is deprecated; use page_size=...", DeprecationWarning, stacklevel=2, # blame the caller's line, not this one ) page_size = limit return list(range(page_size or 3)) # Record warnings instead of printing them, like a test wouldwith warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") fetch_users(limit=2)for w in caught: print(w.category.__name__, "at line", w.lineno, "-", w.message) # Turn warnings into errors, like `python -W error` or a strict CI runwith warnings.catch_warnings(): warnings.simplefilter("error", DeprecationWarning) try: fetch_users(limit=2) except DeprecationWarning as e: print("now an exception:", e) @warnings.deprecated("use page_size instead") # 3.13+def old_api(): return "still works" with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") print(old_api(), "|", caught[0].message)
Output
Press Run (⌘ Enter) to see what happens.

What you need to know to use them well:

  • Categories. DeprecationWarning is aimed at developers and is hidden by default unless the warning is triggered by code in __main__ (or you run tests, where pytest shows it). FutureWarning is shown to everyone; use it when end users must change something. UserWarning is the default category, and RuntimeWarning covers dubious runtime behaviour.
  • stacklevel=2 points the warning at the line that called your function. Without it, every warning points at your own warnings.warn line, which tells the caller nothing.
  • Filters. python -W error (or the PYTHONWARNINGS environment variable) turns warnings into exceptions. In pytest, set filterwarnings = ["error"] in the config so new deprecations fail CI the day they appear, and add ignore entries for specific third-party warnings you cannot fix yet. pytest.warns(DeprecationWarning) asserts that a warning happens.
  • @warnings.deprecated (3.13) marks a function or class in one line, warns at runtime, and is understood by type checkers, which flag uses in the editor.

The point of warnings is the upgrade path. Teams that run their test suite with warnings as errors find out about a removed API a release early, instead of on upgrade day.

Newer syntax: brackets optional, finally stricter

Python 3.14 changed two things in this area (What Changed in Python 3.11 to 3.15 has the full release story):

  • except A, B: without brackets is now legal, as long as there is no as. With as you still write except (A, B) as e:. Code that must run on 3.13 or older still needs the brackets, so most libraries will keep writing them for years.
  • return, break or continue in a finally block now produces a SyntaxWarning. They were always a trap: leaving a finally that way discards the exception that was propagating.
Python
import warnings source = '''def save(): try: raise ConnectionError("disk full") finally: return "saved"''' with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") code = compile(source, "save.py", "exec")print(caught[0].category.__name__, "-", caught[0].message) namespace = {}exec(code, namespace)print(namespace["save"]()) # the ConnectionError is gone
Output
Press Run (⌘ Enter) to see what happens.

The caller is told the save worked while the disk was full. Keep finally for cleanup only, and put any return after the try statement.

Predict the outputPython

What does this print?

def check():
  try:
      1 / 0
  finally:
      return "fine"

print(check())
Need a nudge? Hints walk you through it.
ChallengeEasy

Parse what you can

A form sends you a list of strings. Return a list of the ones that are valid integers, converted to int, in their original order. Skip anything int() cannot parse.

Use EAFP: try int(text) and catch only the error it raises for bad input. (int already accepts surrounding spaces and a leading sign.)

parse_ints(["1", "two", " 3 ", "-4", "5.0"])   # [1, 3, -4]
Python
def parse_ints(items: list[str]) -> list[int]: # Try int() on each item; skip the ones that raise. pass
ChallengeMedium

Inventory exceptions

Design a small exception hierarchy for an inventory module.

  • InventoryError(Exception): the base class for this module.
  • UnknownItem(InventoryError): the item is not in stock at all.
  • OutOfStock(InventoryError): built as OutOfStock(item, requested, available). It stores those three as attributes and its message (str(e)) is "only {available} {item} left".

Then write take(stock, item, qty), where stock is a dict of item name to count:

  • If item is missing, raise UnknownItem chained from the original KeyError (use raise ... from).
  • If qty is more than what is available, raise OutOfStock.
  • Otherwise subtract qty from the stock (mutating the dict) and return the remaining count.
stock = {"apple": 5}
take(stock, "apple", 2)    # 3, and stock is now {"apple": 3}
take(stock, "apple", 9)    # OutOfStock: only 3 apple left
take(stock, "pear", 1)     # UnknownItem, with __cause__ a KeyError
Python
class InventoryError(Exception): pass # Define UnknownItem and OutOfStock here. def take(stock: dict[str, int], item: str, qty: int) -> int: pass
Key terms
exception
An object raised to signal an error; it propagates up the call stack until caught.
traceback
The report of the call chain that led to an uncaught exception, most recent call last.
finally
A block that always runs when leaving a try, used for cleanup.
raise ... from
Raises a new exception while recording the original as its __cause__.
EAFP
Easier to ask forgiveness than permission: try the operation and catch the specific failure.
custom exception
A subclass of Exception (often of your own base class) that callers can catch precisely.