Skip to main content
Editor

Python Custom Exceptions: Build Your Own Error Types

Intermediate20 min5 exercises75 XP
0/5 exercises

Imagine your car's dashboard had only one warning light that just said "Problem." Not very helpful, right? You'd want to know: is the engine overheating? Is the oil low? Is a door open? The more specific the warning, the faster you can fix the issue.

Python's built-in exceptions like ValueError and TypeError are like generic warning lights. They tell you something is wrong, but they don't speak the language of your application. When you're building a banking app, wouldn't it be more useful to see InsufficientFundsError than a plain ValueError?

In this tutorial, you'll learn to create your own exception types that describe exactly what went wrong in your specific application. This is how professional Python developers write clean, maintainable error handling.

Why Create Custom Exceptions?

Let's look at a function that uses only built-in exceptions:

Using generic ValueError for everything
def withdraw(balance, amount):
if amount <= 0:
raise ValueError("Amount must be positive")
if amount > balance:
raise ValueError("Not enough funds")
return balance - amount
try:
new_balance = withdraw(100, 200)
except ValueError as e:
print(f"Error: {e}")
Output
Error: Not enough funds

The problem here is that both errors are ValueError. The calling code can't easily tell the difference between "invalid amount" and "insufficient funds." It has to read the error message string, which is fragile and ugly.

Custom exceptions solve this by giving each error its own type. The calling code can catch exactly the error it cares about:

Custom exceptions make errors clear
class InvalidAmountError(Exception):
pass
class InsufficientFundsError(Exception):
pass
def withdraw(balance, amount):
if amount <= 0:
raise InvalidAmountError("Amount must be positive")
if amount > balance:
raise InsufficientFundsError(f"Tried to withdraw {amount}, but only {balance} available")
return balance - amount
try:
new_balance = withdraw(100, 200)
except InsufficientFundsError as e:
print(f"Not enough money: {e}")
except InvalidAmountError as e:
print(f"Bad amount: {e}")
Output
Not enough money: Tried to withdraw 200, but only 100 available

Now the caller can handle each situation differently. Maybe insufficient funds shows a "deposit more" button, while an invalid amount shows a "please enter a positive number" message. Custom exceptions make this easy.

How to Create a Basic Custom Exception

A custom exception is just a class that inherits from Exception (or one of its subclasses). The simplest version needs only two lines:

Simplest custom exception
class NegativeNumberError(Exception):
pass
# Using it
try:
raise NegativeNumberError("Expected a positive number")
except NegativeNumberError as e:
print(f"Caught: {e}")
Output
Caught: Expected a positive number

The pass keyword means "this class has no extra code." It inherits everything it needs from Exception - the ability to store a message, be raised, and be caught.

By convention, custom exception class names end with Error. This makes them instantly recognizable in code.

Let's see a practical example. Here's a password validator that uses a custom exception:

Password validator with custom exception
class WeakPasswordError(Exception):
pass
def validate_password(password):
if len(password) < 8:
raise WeakPasswordError("Password must be at least 8 characters")
if password.isalpha():
raise WeakPasswordError("Password must contain at least one number")
return True
passwords = ["hi", "password", "secure123"]
for pw in passwords:
try:
validate_password(pw)
print(f" \"{pw}\" is valid")
except WeakPasswordError as e:
print(f" \"{pw}\" rejected: {e}")
Output
  "hi" rejected: Password must be at least 8 characters
  "password" rejected: Password must contain at least one number
  "secure123" is valid

How to Add Data to Custom Exceptions

The real power of custom exceptions comes from adding your own attributes. Instead of just a message string, you can attach any data the caller needs to handle the error properly.

You do this by adding an __init__ method to your exception class. Just remember to call super().__init__() to keep the normal exception behavior working.

Exception with extra data
class InsufficientFundsError(Exception):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
self.deficit = amount - balance
super().__init__(
f"Cannot withdraw ${amount}. "
f"Balance is ${balance}. "
f"Short by ${self.deficit}."
)
try:
balance = 150
amount = 200
if amount > balance:
raise InsufficientFundsError(balance, amount)
except InsufficientFundsError as e:
print(f"Error: {e}")
print(f"You need ${e.deficit} more")
Output
Error: Cannot withdraw $200. Balance is $150. Short by $50.
You need $50 more

Now the caller doesn't have to parse a string to figure out the numbers. The balance, amount, and deficit are all available as clean attributes on the exception object.

Here's another example with a validation error that tracks which field failed:

ValidationError with field tracking
class ValidationError(Exception):
def __init__(self, field, value, reason):
self.field = field
self.value = value
self.reason = reason
super().__init__(f"Invalid {field}: {reason}")
def validate_user(name, age):
if not name.strip():
raise ValidationError("name", name, "cannot be empty")
if not isinstance(age, int) or age < 0:
raise ValidationError("age", age, "must be a non-negative integer")
if age > 150:
raise ValidationError("age", age, "seems unrealistic")
return {"name": name, "age": age}
test_cases = [("", 25), ("Alice", -3), ("Bob", 200), ("Charlie", 30)]
for name, age in test_cases:
try:
user = validate_user(name, age)
print(f"Created user: {user}")
except ValidationError as e:
print(f"Failed on field \'{e.field}\': {e.reason} (got {e.value!r})")
Output
Failed on field 'name': cannot be empty (got '')
Failed on field 'age': must be a non-negative integer (got -3)
Failed on field 'age': seems unrealistic (got 200)
Created user: {'name': 'Charlie', 'age': 30}

Building Exception Hierarchies

When your application has many custom exceptions, you can organize them into a hierarchy using inheritance. This lets callers choose how specific their error handling should be.

Think of it like a filing system. You might have a general "Application Error" folder, with sub-folders for "Payment Error" and "User Error," and even more specific folders inside those.

Exception hierarchy in action
# Base exception for our entire application
class AppError(Exception):
pass
# Payment-related errors
class PaymentError(AppError):
pass
class InsufficientFundsError(PaymentError):
pass
class CardDeclinedError(PaymentError):
pass
# User-related errors
class UserError(AppError):
pass
class UserNotFoundError(UserError):
pass
class PermissionDeniedError(UserError):
pass
# Catching at different levels
def test_hierarchy():
errors = [
InsufficientFundsError("Not enough funds"),
CardDeclinedError("Card was declined"),
UserNotFoundError("User does not exist"),
]
for error in errors:
try:
raise error
except PaymentError as e:
print(f"Payment issue: {e}")
except UserError as e:
print(f"User issue: {e}")
test_hierarchy()
Output
Payment issue: Not enough funds
Payment issue: Card was declined
User issue: User does not exist

Notice that except PaymentError catches both InsufficientFundsError and CardDeclinedError because they both inherit from PaymentError. This is the power of hierarchies - you can catch broadly or narrowly, depending on what makes sense.

You could also catch at the very top with except AppError to handle any error from your application, while still letting system errors (like MemoryError) pass through.

Here's a diagram showing the hierarchy as a tree. Each level inherits from the one above:

Verifying the hierarchy with isinstance
# Exception hierarchy tree:
#
# AppError
# ├── PaymentError
# │ ├── InsufficientFundsError
# │ └── CardDeclinedError
# └── UserError
# ├── UserNotFoundError
# └── PermissionDeniedError
# You can verify the hierarchy with isinstance:
error = InsufficientFundsError("test")
print(f"Is PaymentError? {isinstance(error, PaymentError)}")
print(f"Is AppError? {isinstance(error, AppError)}")
print(f"Is UserError? {isinstance(error, UserError)}")
print(f"Is Exception? {isinstance(error, Exception)}")
Output
Is PaymentError? True
Is AppError? True
Is UserError? False
Is Exception? True

An InsufficientFundsError is also a PaymentError, also an AppError, and also an Exception. This chain of "is-a" relationships is what makes hierarchies so powerful for error handling.

Real-World Custom Exception Patterns

Let's put it all together with a more realistic example. Here's a simple user registration system with a clean exception hierarchy:

User registration with custom exceptions
class RegistrationError(Exception):
"""Base error for registration problems."""
pass
class UsernameError(RegistrationError):
def __init__(self, username, reason):
self.username = username
self.reason = reason
super().__init__(f"Username \'{username}\': {reason}")
class EmailError(RegistrationError):
def __init__(self, email, reason):
self.email = email
self.reason = reason
super().__init__(f"Email \'{email}\': {reason}")
# Simulated database of existing users
existing_users = {"alice", "bob"}
existing_emails = {"alice@mail.com"}
def register(username, email):
# Validate username
if len(username) < 3:
raise UsernameError(username, "must be at least 3 characters")
if not username.isalnum():
raise UsernameError(username, "must contain only letters and numbers")
if username.lower() in existing_users:
raise UsernameError(username, "already taken")
# Validate email
if "@" not in email:
raise EmailError(email, "must contain @")
if email.lower() in existing_emails:
raise EmailError(email, "already registered")
return f"User {username} registered with {email}"
# Test different scenarios
test_data = [
("ab", "test@mail.com"),
("alice", "new@mail.com"),
("charlie", "invalid-email"),
("dave", "alice@mail.com"),
("eve", "eve@mail.com"),
]
for username, email in test_data:
try:
result = register(username, email)
print(f"Success: {result}")
except UsernameError as e:
print(f"Username problem: {e.reason}")
except EmailError as e:
print(f"Email problem: {e.reason}")
Output
Username problem: must be at least 3 characters
Username problem: already taken
Email problem: must contain @
Email problem: already registered
Success: User eve registered with eve@mail.com

This pattern gives you three levels of control. You can catch UsernameError or EmailError for specific handling. Or catch RegistrationError to handle all registration problems the same way.

Another useful pattern is creating exceptions that suggest a fix:

Exceptions that suggest fixes
class ConfigError(Exception):
def __init__(self, key, suggestion=None):
self.key = key
self.suggestion = suggestion
message = f"Missing config key: \'{key}\'"
if suggestion:
message += f". Did you mean \'{suggestion}\'?"
super().__init__(message)
# Simulated config
config = {"database_url": "localhost", "debug_mode": True}
valid_keys = set(config.keys())
def get_config(key):
if key not in config:
# Find similar keys for suggestions
for valid_key in valid_keys:
if key.lower() in valid_key.lower() or valid_key.lower() in key.lower():
raise ConfigError(key, suggestion=valid_key)
raise ConfigError(key)
return config[key]
try:
get_config("database")
except ConfigError as e:
print(e)
if e.suggestion:
print(f"Trying suggested key: {e.suggestion}")
print(f"Value: {get_config(e.suggestion)}")
Output
Missing config key: 'database'. Did you mean 'database_url'?
Trying suggested key: database_url
Value: localhost

Practice Exercises

Create a Custom Exception
Write Code

Create a custom exception class called NegativeAgeError that inherits from Exception.

Then write a function called set_age(age) that raises NegativeAgeError with the message "Age cannot be negative: X" (where X is the age) if the age is negative. Otherwise, it prints "Age set to X".

Test it with set_age(25) and catch the error from set_age(-5).

# Create your NegativeAgeError class
# Write the set_age function
# Test with 25 and -5
Predict the Exception Hierarchy
Predict Output

Read the code below and predict what it will print.

class AppError(Exception):
    pass

class DatabaseError(AppError):
    pass

class ConnectionError(DatabaseError):
    pass

errors = [ConnectionError("timeout"), DatabaseError("corrupt"), AppError("unknown")]

for e in errors:
    try:
        raise e
    except ConnectionError:
        print("connection")
    except DatabaseError:
        print("database")
    except AppError:
        print("app")
# Type the exact output using print statements
Exception with Extra Data
Write Code

Create a custom exception called TemperatureError with:

  • An __init__ that accepts temp and unit parameters
  • Stores self.temp and self.unit
  • Passes the message "Invalid temperature: X Y" to super().__init__() (where X is temp and Y is unit)
  • Then write a function check_water_temp(temp) that:

  • Raises TemperatureError(temp, "C") with message if temp < 0 or temp > 100
  • Prints "Water is liquid at X C" otherwise
  • Test with check_water_temp(50), then catch errors from check_water_temp(-10) and print both the error message AND the temp attribute.

    # Create TemperatureError class
    # Write check_water_temp function
    # Test it
    Build a Shopping Cart Exception Hierarchy
    Write Code

    Create an exception hierarchy for a shopping cart:

    1. CartError(Exception) - base class (just pass)

    2. EmptyCartError(CartError) - just pass

    3. ItemNotFoundError(CartError) - accepts item_name in __init__, stores it as self.item_name, message: "Item not found: X"

    Then write a function checkout(cart) that:

  • Raises EmptyCartError("Cart is empty") if the cart list is empty
  • Prints "Checking out N items" where N is the number of items
  • And a function remove_item(cart, item) that:

  • Raises ItemNotFoundError(item) if the item is not in the cart
  • Otherwise removes it and prints "Removed: X"
  • Test:

    1. Call checkout([]) and catch EmptyCartError

    2. Call remove_item(["apple", "bread"], "milk") and catch ItemNotFoundError, printing the item_name attribute

    3. Call checkout(["apple", "bread"]) (success)

    # Build the exception hierarchy
    # Write checkout and remove_item functions
    # Test all three cases
    Refactor: Replace Generic with Custom Exceptions
    Refactor

    The code below uses generic ValueError for all errors. Refactor it to use custom exceptions.

    Create:

  • GradeError(Exception) - base class, just pass
  • InvalidGradeError(GradeError) - accepts grade in __init__, stores as self.grade, message: "Invalid grade: X"
  • InvalidSubjectError(GradeError) - accepts subject in __init__, stores as self.subject, message: "Unknown subject: X"
  • Replace the ValueError raises with the appropriate custom exceptions. Update the except blocks to catch InvalidGradeError and InvalidSubjectError separately.

    The output should remain exactly the same.

    # Original code - refactor this to use custom exceptions
    VALID_SUBJECTS = ["math", "science", "english"]
    def add_grade(subject, grade):
    if subject not in VALID_SUBJECTS:
    raise ValueError(f"Unknown subject: {subject}")
    if not isinstance(grade, (int, float)) or grade < 0 or grade > 100:
    raise ValueError(f"Invalid grade: {grade}")
    print(f"Added grade {grade} for {subject}")
    test_data = [("math", 95), ("art", 80), ("science", 150), ("english", 88)]
    for subject, grade in test_data:
    try:
    add_grade(subject, grade)
    except ValueError as e:
    print(f"Error: {e}")

    Harder problems

    More problems on this topic: Classes

    Related Tutorials

    Was this tutorial helpful?