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

Python Custom Exceptions

A custom exception is an error type you invent yourself with a name that fits your program, like a special warning sign for your own playground. It makes problems easier to understand.
Syntax
python
class CustomError(Exception):
    pass

raise CustomError("message")

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):  # custom exception type
    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)  # passes the message to the base Exception

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")  # triggers the custom exception

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:  # catches the custom type like any built-in one
    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  # extra structured detail beyond the message

try:
    raise InsufficientFundsError("balance too low", 402)
except InsufficientFundsError as e:
    print(e, e.error_code)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Not inheriting from Exception, as in class MyError:, which cannot be raised and gives TypeError.
  2. Catching the base Exception first, so the more specific custom exception in a later except never runs.
  3. Overriding __init__ without calling super().__init__(message), so the message is missing when the error is printed.
🔒

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.