Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
raise sends an error and except receives it. Follow an error up the call stack, use the exception family tree, re-raise and chain errors with raise from, and build InsufficientFundsError and an AppError family of your own.
What you will learn
- Tell raise from except, and follow an error as it climbs the call stack
- Use the exception class tree to order except blocks and avoid bare except
- Re-raise an error, and change its type with raise from while keeping the cause
- Write custom exceptions that carry data, grouped under one parent
Before you start
- try and except basics
- Python classes and inheritance
You've seen try and except deal with a problem in one place. Now follow that problem from the moment it's sent to the moment it's handled, and along the way write errors of your own. One thing to keep clear the whole time: raise and except are two different jobs.
raise sends, except receives
Think about a shop. A cashier hits a problem she can't solve, so she writes a note and sends it up. It reaches the supervisor, who only deals with refunds; this isn't a refund, so he passes it on. The manager does deal with this kind of problem, so she takes the note and it stops there. raise is the cashier sending the note. except is the desk that receives it.
def set_age(age):
if age < 0:
raise ValueError("age cannot be negative")
return age
print(set_age(30))
try:
set_age(-5)
except ValueError as e:
print("caught:", e)
30
caught: age cannot be negative
-5 is a valid number for Python but not a valid age for us. raise ValueError(...) builds an error object with our message and sends it. The function stops there, so return age never runs. You write raise where you spot the problem, and except where you can deal with it.
When nobody receives it
def read_age(text):
return int(text)
def load_user(text):
return read_age(text)
def main():
print(load_user("abc"))
main()
Traceback (most recent call last):
File "S04L01_Exceptions\uncaught.py", line 13, in <module>
main()
~~~~^^
File "S04L01_Exceptions\uncaught.py", line 10, in main
print(load_user("abc"))
~~~~~~~~~^^^^^^^
File "S04L01_Exceptions\uncaught.py", line 6, in load_user
return read_age(text)
File "S04L01_Exceptions\uncaught.py", line 2, in read_age
return int(text)
ValueError: invalid literal for int() with base 10: 'abc'
Each call sits on top of the last one, and that pile is the call stack. int raises, there's no except in read_age, so the error climbs to load_user, then main, then the top of the file. Nobody received it, so the program stops. Read a traceback from the bottom: the last line says what went wrong, and the lines above show the path, oldest call first.
The exception family tree
Exceptions are classes, so they have parents, just like any inheritance.
def chain(cls):
return " -> ".join(c.__name__ for c in cls.__mro__)
print(chain(ZeroDivisionError))
print(chain(KeyError))
print(chain(FileNotFoundError))
print(chain(KeyboardInterrupt))
ZeroDivisionError -> ArithmeticError -> Exception -> BaseException -> object
KeyError -> LookupError -> Exception -> BaseException -> object
FileNotFoundError -> OSError -> Exception -> BaseException -> object
KeyboardInterrupt -> BaseException -> object
They all meet at Exception, except KeyboardInterrupt, which goes straight to BaseException. Remember that one. The tree matters because an except matches its own class and every child below it, so except LookupError receives a KeyError too.
Both trees together
def level3():
print("level3: raising KeyError")
raise KeyError("id")
def level2():
print("level2: calling level3")
try:
level3()
except ValueError:
print("level2: handled")
print("level2: finished")
def level1():
print("level1: calling level2")
try:
level2()
except LookupError as e:
print("level1: caught", type(e).__name__)
print("level1: carries on")
level1()
level1: calling level2
level2: calling level3
level3: raising KeyError
level1: caught KeyError
level1: carries on
Notice "level2: finished" never prints. The error leaves the function at once. Once level1 catches it, the error is gone and level1 carries on normally.
Several excepts, and their order
def parse_port(config):
try:
port = int(config["port"])
except KeyError:
return "missing port"
except (ValueError, TypeError) as e:
return f"bad port: {e}"
return port
print(parse_port({}))
print(parse_port({"port": "80a"}))
print(parse_port({"port": None}))
print(parse_port({"port": "8080"}))
missing port
bad port: invalid literal for int() with base 10: '80a'
bad port: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
8080
Three forms: one except for one error, a tuple so two errors share a block, and as e to read the message. For the same handling use one tuple; for different handling, separate blocks.
Python checks the blocks top to bottom and the first match wins. Put except Exception first and a ValueError lands there, printing "general handler ran"; the ValueError block below can never run, and Python won't warn you. Swap them and you get "specific handler ran". Specific on top, general at the bottom.
Why never a bare except
import sys
print("start")
try:
sys.exit(1)
except:
print("bare except swallowed SystemExit")
print("still running")
start
bare except swallowed SystemExit
still running
sys.exit works by raising SystemExit, and the bare except grabs it, so a program told to stop keeps running. Ctrl+C (KeyboardInterrupt) gets grabbed the same way. With except Exception instead, SystemExit goes straight past, because it sits under BaseException; that version prints only "start" and exits with code 3. If you need a general handler, write except Exception.
Note it and send it on: a plain raise
def set_age(age):
if age < 0:
raise ValueError("age cannot be negative")
return age
def save(age):
try:
return set_age(age)
except ValueError as e:
print("save: could not set age:", e)
raise
try:
save(-5)
except ValueError:
print("caller: still got the error")
save: could not set age: age cannot be negative
caller: still got the error
raise on its own sends the same error on its way up. In a bigger app, the print is where you'd write to a log (see logging and debugging). Leave that raise out and the caller thinks everything went fine.
Change the error, keep the cause: raise from
def load_port(text):
try:
return int(text)
except ValueError as e:
raise RuntimeError("Config parse failed") from e
try:
load_port("abc")
except RuntimeError as e:
print("error:", e)
print("cause:", repr(e.__cause__))
error: Config parse failed
cause: ValueError("invalid literal for int() with base 10: 'abc'")
The caller doesn't care about int; it wants to know the config failed. So we raise a new RuntimeError, and from e ties the old error to it as __cause__. If nobody catches it, the traceback shows both:
Traceback (most recent call last):
File "S04L01_Exceptions\chained_crash.py", line 3, in load_port
return int(text)
ValueError: invalid literal for int() with base 10: 'abc'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "S04L01_Exceptions\chained_crash.py", line 8, in <module>
load_port("abc")
~~~~~~~~~^^^^^^^
File "S04L01_Exceptions\chained_crash.py", line 5, in load_port
raise RuntimeError("Config parse failed") from e
RuntimeError: Config parse failed
Leave out from e and Python still keeps the old error, but the middle line becomes "During handling of the above exception, another exception occurred". That reads like your except block had a bug of its own. Writing from e says you meant it. When the old error is only noise, write from None; then __cause__ is None and an uncaught traceback shows only the new error.
Your own exceptions
ValueError could mean almost anything. A custom exception says exactly what went wrong and carries the details.
class InsufficientFundsError(Exception):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(
f"Cannot withdraw ${amount}. "
f"Balance: ${balance}"
)
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(balance, amount)
return balance - amount
print(withdraw(300, 100))
try:
withdraw(100, 250)
except InsufficientFundsError as e:
print(e)
print(f"Short by: ${e.amount - e.balance}")
200
Cannot withdraw $250. Balance: $100
Short by: $150
Inheriting from Exception is what makes it an exception. super().__init__ gets the message so printing reads well, and the values ride along on the object so the caller can work out the shortfall.
A family of app errors
class AppError(Exception):
"""Base for all app errors."""
class ValidationError(AppError):
pass
class AuthenticationError(AppError):
pass
class DatabaseError(AppError):
pass
def do_work(error):
raise error("details")
errors = [AuthenticationError, DatabaseError, KeyError]
for error in errors:
try:
do_work(error)
except AuthenticationError:
print("Login failed")
except AppError as e:
print(f"App error: {e}")
except KeyError:
print("Not one of ours")
print(issubclass(ValidationError, Exception))
Login failed
App error: details
Not one of ours
True
DatabaseError has no block, so it matches its parent AppError. KeyError isn't in the family, so AppError skips it. Callers can catch one child or the whole family, and other errors stay out of it.
Errors and files: finally or with
If an error happens while a file is open, something has to close it. With try/finally you write the close yourself: inside the except the file still reports closed as False, and after finally it's True. with open does it for you:
with open("notes.txt", "w") as f:
f.write("first line\n")
try:
with open("notes.txt") as f:
print(f.readline().strip())
1 / 0
except ZeroDivisionError:
print("caught, closed?", f.closed)
first line
caught, closed? True
The file closes on the way out of the block, before except runs. with doesn't catch the error; you still need except for that.
The most expensive mistake: swallowing errors
def total(prices):
try:
return sum(prices) + bonus
except Exception:
pass
print(total([5, 10]))
None
bonus was never defined. That's a NameError, and except Exception: pass grabs it and says nothing. No message, no clue, just a wrong answer. Catch only the TypeError you expect, and the NameError climbs out with a traceback that ends NameError: name 'bonus' is not defined. A crash you can read is far better than a quiet wrong answer.
Rules to check AI-written error handling against
- Catch specific errors. Never a bare
except. - Keep
tryblocks small; put success code inelse. - Use
finallyorwithfor cleanup. - Never silence an error with
pass. At least log it and raise it again. - When you change an error's type, use
raise ... from e. - Group your app's custom exceptions under one parent.
- Don't use
tryfor normal cases. If a key may be missing,dict.getis simpler.
Try it yourself
Write an OutOfStockError that carries the item, the count wanted and the count left. Raise it from a buy function and catch it by name, plus KeyError for unknown items. With stock {"pen": 5, "book": 0} and orders for 2 pens, 1 book and 1 bag, one solution prints:
pen left: 3
Sorry: book: wanted 1, only 0 left
No such item: 'bag'Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Set Up a Python AI Project with uv, VS Code and an API Key in .env
One environment for every AI project: uv brings Python 3.12 and pinned packages from uv.lock, a check script fails four times on plain python and passes after uv sync, VS Code points at .venv, the API key stays in .env, and a stand-in test model answers when there is no key.
uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
One tool instead of venv, activate, pip install and pip freeze. Build a small chatbot project with uv init, hit ModuleNotFoundError, fix it with uv add, read pyproject.toml and uv.lock, then delete .venv and rebuild it with uv sync.
Python try and except Basics: Catch an Error and Keep Going
An exception is the object Python creates when something goes wrong. Catch it with try and a named except, read it with as, add else and finally, retry bad input in a loop, and see why a bare except hides your bugs.
Read and Write a File in Python: open, with, Modes and Encoding
Make your data outlive the program: write notes.txt with open and with, read it back three ways, see how w wipes a file and a appends, why encoding matters, and what to do when a file isn't there.
