Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Modules, Files and Errors

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Modules, Files and Errors

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
A KeyError raised in level3 climbs the call stack: level2's except ValueError does not match, level1's except LookupError matches because KeyError is a child of LookupError, so it stops there level3 raise KeyError("id") level2 except ValueError: no match level1 except LookupError: match, stop the error climbs family tree LookupError KeyError "level2: finished" never prints
The error climbs the call stack; each except checks the family tree; the first match stops it.

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 try blocks small; put success code in else.
  • Use finally or with for 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 try for normal cases. If a key may be missing, dict.get is 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'

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 29 of 48

Previous
Read and Write a File in Python: open, with, Modes and Encoding
Next post
Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()

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.

On this page

  • raise sends, except receives
  • When nobody receives it
  • The exception family tree
  • Both trees together
  • Several excepts, and their order
  • Why never a bare except
  • Note it and send it on: a plain raise
  • Change the error, keep the cause: raise from
  • Your own exceptions
  • A family of app errors
  • Errors and files: finally or with
  • The most expensive mistake: swallowing errors
  • Rules to check AI-written error handling against
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.