Raising Exceptions

Signal errors in your own code with raise.

Syntaxraise ValueError('message')

You can trigger an exception yourself with the raise keyword. This is how you report that something is wrong, such as an invalid argument.

Choosing an exception

  • ValueError — a value is the right type but unacceptable.
  • TypeError — a value is the wrong type.

You can also define your own exception by subclassing Exception.

Example

Example · python
def set_age(age):
    if age < 0:
        raise ValueError('Age cannot be negative')
    return age

try:
    set_age(-5)
except ValueError as e:
    print('Error:', e)

# Output:
# Error: Age cannot be negative

When to use it

  • A library raises ValueError with a descriptive message when an argument is outside the valid range.
  • An ORM raises a custom DatabaseError subclass so callers can catch it separately from built-in errors.
  • A public API validates input at its boundary and raises TypeError before any processing begins.

More examples

Raise a built-in exception

Raises ValueError with a descriptive message when the caller passes an invalid age.

Example · python
def set_age(age):
    if not isinstance(age, int) or age < 0:
        raise ValueError(f'Invalid age: {age!r}')
    return age

try:
    set_age(-5)
except ValueError as e:
    print('Error:', e)

# Output:
# Error: Invalid age: -5

Custom exception class

Defines a domain-specific exception so callers can catch it independently of other errors.

Example · python
class InsufficientFundsError(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError(
            f'Need {amount}, only {balance} available')
    return balance - amount

try:
    withdraw(50, 100)
except InsufficientFundsError as e:
    print(e)

Re-raise inside except

Logs the error for observability and then re-raises so the caller can decide what to do.

Example · python
import logging

def load_config(path):
    try:
        with open(path) as f:
            return f.read()
    except FileNotFoundError:
        logging.error('Config file not found: %s', path)
        raise  # re-raise for the caller to handle

try:
    load_config('missing.cfg')
except FileNotFoundError:
    print('Startup aborted: config missing')

Discussion

  • Be the first to comment on this lesson.