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.
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.
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.
Press Run (⌘ Enter) to see what happens.excepthandles a specific error type. You can have several, checked top to bottom, and catch more than one type with a tuple:except (KeyError, IndexError):.elseruns only when no exception happened. It keeps thetryblock small, so you do not accidentally catch errors from code you did not mean to guard.finallyruns no matter what: success, exception,returnorbreak. It is for cleanup like closing connections (thoughwithusually does that better).
A try block succeeds and contains a return. In what order do the parts run?
- Tap the steps below in the right order.
What does this print?
def f():
try:
return "try"
finally:
print("cleanup")
print(f())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.
Almost every error you will handle inherits from Exception. Your own exceptions should too.
try:
{}["missing"]
except LookupError:
print("lookup")
except KeyError:
print("key")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.
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__.
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.
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
exceptonly 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
exceptandexcept*in onetry, and you cannot usereturn,breakorcontinueinside anexcept*block. Each is aSyntaxError. - Plain
except ExceptionGroupstill works if you want the whole group at once, andeg.split(Type)oreg.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():
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.
ValueError on one row, and callers already handle ValueError. You want the traceback to show the row number. What is the best change?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 = ""try:
with open(path) as f:
data = f.read()
except FileNotFoundError:
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.
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 happenedThe customer is not charged, nobody knows, and a typo in charge_customer looks identical to a declined card. The rules:
- Catch the narrowest exception you can actually handle.
- Never use bare
except:. If you truly need a catch-all at the top of a program, useexcept Exceptionand log it with the traceback. - Keep the
tryblock as small as possible. - If you cannot do anything useful about an error, let it propagate.
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:
One base class per package. A caller who just wants 'anything from billing' writes one except BillingError, and never has to know your internals.
The design rules that go with it:
- Wrap third-party errors at your boundary. If your billing package lets an
httpx.ConnectTimeoutescape, every caller now depends onhttpx, and switching HTTP client breaks them. Catch it inside andraise ProviderTimeout(...) from e. The original stays in the traceback. - Catch broadly only at the edges.
except Exceptionbelongs 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. - Map to the outside world in one place. Route handlers should not each translate
CustomerNotFoundinto a 404. Register one handler that maps your hierarchy to HTTP status codes (FastAPI'sexception_handlerdoes this). - 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.
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.)
httpx. Where should httpx.ConnectTimeout be handled?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.
Press Run (⌘ Enter) to see what happens.What you need to know to use them well:
- Categories.
DeprecationWarningis 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).FutureWarningis shown to everyone; use it when end users must change something.UserWarningis the default category, andRuntimeWarningcovers dubious runtime behaviour. stacklevel=2points the warning at the line that called your function. Without it, every warning points at your ownwarnings.warnline, which tells the caller nothing.- Filters.
python -W error(or thePYTHONWARNINGSenvironment variable) turns warnings into exceptions. In pytest, setfilterwarnings = ["error"]in the config so new deprecations fail CI the day they appear, and addignoreentries 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 noas. Withasyou still writeexcept (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,breakorcontinuein afinallyblock now produces aSyntaxWarning. They were always a trap: leaving afinallythat way discards the exception that was propagating.
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.
What does this print?
def check():
try:
1 / 0
finally:
return "fine"
print(check())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]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 asOutOfStock(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
itemis missing, raiseUnknownItemchained from the originalKeyError(useraise ... from). - If
qtyis more than what is available, raiseOutOfStock. - Otherwise subtract
qtyfrom 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- 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.