← Back to Python Course | Chapter 10: Exception Handling | Lesson 4 of 5

Python Custom Exceptions

Creating a Custom Exception

Defining a new class that inherits from the built-in Exception class creates a custom exception type -- even an empty 'class InsufficientFundsError(Exception): pass' is immediately usable with raise and except, giving your errors a name specific to your application's domain.

Example: Creating a Custom Exception

python
class InsufficientFundsError(Exception):
    pass

try:
    raise InsufficientFundsError()
except InsufficientFundsError:
    print("Custom exception caught")

Adding Custom Messages

Overriding __init__ to accept a message and passing it to the parent class via super().__init__(message) lets your custom exception carry a description just like built-in exceptions do, so str(my_exception) returns something meaningful instead of being blank.

Example: Adding Custom Messages

python
class InsufficientFundsError(Exception):
    def __init__(self, message):
        super().__init__(message)

try:
    raise InsufficientFundsError("balance too low")
except InsufficientFundsError as e:
    print(str(e))

Raising Custom Exceptions

You trigger a custom exception the same way as a built-in one -- raise InsufficientFundsError('balance too low') -- which immediately stops normal execution and looks for a matching except block up the call stack.

Example: Raising Custom Exceptions

python
class InsufficientFundsError(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError("balance too low")

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

Catching Custom Exceptions

Catching a custom exception works exactly like catching a built-in one: 'except InsufficientFundsError as e:' -- this lets calling code respond specifically to your application's own error conditions rather than generic ones.

Example: Catching Custom Exceptions

python
class InsufficientFundsError(Exception):
    pass

try:
    raise InsufficientFundsError("Not enough money")
except InsufficientFundsError as e:
    print("Caught:", e)

Adding Custom Attributes

Beyond the message, you can attach extra attributes to a custom exception in its __init__ (like self.error_code = code), letting except blocks that catch it access structured details about exactly what went wrong, not just a human-readable string.

Example: Adding Custom Attributes

python
class InsufficientFundsError(Exception):
    def __init__(self, message, error_code):
        super().__init__(message)
        self.error_code = error_code

try:
    raise InsufficientFundsError("balance too low", 402)
except InsufficientFundsError as e:
    print(e, e.error_code)
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.