Skip to content
Kuza Ndoto Academy

Raising Exceptions

Beginner → IntermediateChapter 7 · Page 39 of 565 min readUpdated 15 Nov 2026

Python raises exceptions when built-in operations fail, and your own code can do the same. Raising an exception is the clearest way for a function to say "I can't do what you asked, and here's why".

The raise statement

Use raise followed by an exception object, usually with a helpful message. The function stops immediately, just as if Python itself had hit an error.

def withdraw(balance, amount):
    if amount <= 0:
        raise ValueError("Amount must be greater than zero")
    if amount > balance:
        raise ValueError(f"Insufficient funds: balance is KES {balance}, requested KES {amount}")
    return balance - amount

print(withdraw(1000, 300))

for request in [-50, 1500]:
    try:
        withdraw(1000, request)
    except ValueError as error:
        print("Refused:", error)
700 Refused: Amount must be greater than zero Refused: Insufficient funds: balance is KES 1000, requested KES 1500

Why not just print a message and return None? Because the caller might ignore None and carry on with a wrong value. An exception can't be ignored by accident: either someone handles it, or the program stops and shows exactly what went wrong.

If nothing catches a raised exception, you get a normal traceback:

def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    return age

set_age(-5)
Traceback (most recent call last): File "profile.py", line 6, in <module> set_age(-5) File "profile.py", line 3, in set_age raise ValueError("Age cannot be negative") ValueError: Age cannot be negative

Choosing the right exception type

Pick the built-in exception that best describes the problem, so callers can catch it sensibly:

UseWhen
ValueErrorThe type is fine but the value isn't (negative age, empty name)
TypeErrorThe argument is the wrong type entirely (text instead of a number)
KeyError / LookupErrorSomething you looked up doesn't exist
FileNotFoundErrorA required file is missing
PermissionErrorThe user isn't allowed to do this
NotImplementedErrorA method that subclasses are supposed to write
RuntimeErrorSomething went wrong that doesn't fit any other category
def area(width, height):
    if not isinstance(width, (int, float)) or not isinstance(height, (int, float)):
        raise TypeError("width and height must be numbers")
    if width <= 0 or height <= 0:
        raise ValueError("width and height must be positive")
    return width * height

for args in [(4, 5), (4, "5"), (4, -5)]:
    try:
        print(area(*args))
    except (TypeError, ValueError) as error:
        print(f"{type(error).__name__}: {error}")
20 TypeError: width and height must be numbers ValueError: width and height must be positive

Creating your own exceptions

For bigger programs, define custom exception classes. They make error handling more precise, because callers can catch exactly your problem and nothing else. A custom exception is a class that inherits from Exception (classes are explained in Classes & Objects and Inheritance).

class BankError(Exception):
    """Base class for all errors in our banking app."""

class InsufficientFundsError(BankError):
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        shortfall = amount - balance
        super().__init__(f"You need KES {shortfall} more to withdraw KES {amount}")

class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def withdraw(self, amount):
        if amount > self.balance:
            raise InsufficientFundsError(self.balance, amount)
        self.balance -= amount

account = Account("Fatuma", 2000)
try:
    account.withdraw(2600)
except InsufficientFundsError as error:
    print("Error:", error)
    print("Shortfall:", error.amount - error.balance)
except BankError:
    print("Some other banking problem")
Error: You need KES 600 more to withdraw KES 2600 Shortfall: 600

Name custom exceptions with an Error ending. A shared base class (here BankError) lets callers catch every error from your app with one except, or a specific one when they need to.

Re-raising and chaining exceptions

Re-raise with a bare raise

Inside an except block, raise on its own re-raises the current exception. This is handy when you want to log a problem but still let the caller deal with it.

def parse_score(text):
    try:
        return int(text)
    except ValueError:
        print(f"Logging: bad score {text!r}")
        raise

try:
    parse_score("9o")
except ValueError as error:
    print("Caller saw:", error)
Logging: bad score '9o' Caller saw: invalid literal for int() with base 10: '9o'

Translate an error with raise ... from

Sometimes a low-level error should become a clearer, higher-level one. raise NewError(...) from original does this while keeping the original attached as the "cause", so no debugging information is lost.

class InvalidAgeError(Exception):
    pass

def load_age(text):
    try:
        return int(text)
    except ValueError as error:
        raise InvalidAgeError(f"Age must be a number, got {text!r}") from error

try:
    load_age("twenty")
except InvalidAgeError as error:
    print(error)
    print("Caused by:", repr(error.__cause__))
Age must be a number, got 'twenty' Caused by: ValueError("invalid literal for int() with base 10: 'twenty'")

If this exception were not caught, the traceback would show both errors, joined by the line "The above exception was the direct cause of the following exception".

A note on assert

assert condition, "message" raises an AssertionError if the condition is false. It's useful for checking your own assumptions while developing, for example assert total >= 0. Don't use it to validate user input: assertions are skipped completely when Python runs with the -O (optimise) option.

Common mistake

You can only raise exception objects. raise "Something broke" fails with TypeError: exceptions must derive from BaseException. Write raise ValueError("Something broke") instead. Also avoid raising the generic Exception: callers then can't catch your error without catching everything else too.

Key points

  • raise SomeError("message") stops a function and reports a problem.
  • Choose a fitting built-in type, or create a custom class that inherits from Exception.
  • A bare raise inside except re-raises the current exception.
  • raise NewError(...) from error keeps the original error as the cause.
  • Use assert for developer checks, never for validating input.
Up next · New chapter: Object-Oriented PythonClasses & ObjectsModel real things in code.
→

Tip: use the ← and → keys to move between pages.