01 / 21

Custom
Exceptions

Learn how to define your own exception classes in Python to write cleaner, more descriptive error handling for your programs.

Python Programming

What Is an Exception?

An exception is an event that disrupts the normal flow of a program. When Python encounters an error at runtime, it creates an exception object containing information about what went wrong and where it happened.

ValueError
Wrong value passed to a function
TypeError
Operation on incompatible types
KeyError
Missing key in a dictionary

The Exception Hierarchy

Every exception in Python inherits from the BaseException class. For custom exceptions, you always inherit from Exception (not BaseException), which sits one level below.

BaseException Exception ValueError TypeError RuntimeError YourCustomError (inherits from Exception)

Why Create Custom Exceptions?

1
Descriptive names: A WithdrawalLimitError is far clearer than a generic ValueError.
2
Targeted catching: You can catch only your specific error without accidentally catching unrelated ones.
3
Extra data: Attach custom attributes like error codes, thresholds, or user IDs to the exception object.
4
Professional code: Libraries and frameworks define their own exception hierarchies so callers know exactly what to expect.

The Core Pattern

A custom exception is simply a class that inherits from Exception (or one of its subclasses). At its simplest, the body can be just pass.

class MyCustomError(Exception): pass

Anatomy of a Custom Exception

class NegativeAgeError ( Exception ): Your class name Parent class def __init__ ( self , age , message ): super().__init__(message) Passes msg up self . age = age Custom attribute def __str__ ( self ): return f"Age {self.age} is invalid"

Built-in vs Custom Exceptions

Built-in Custom
Definition Pre-defined in Python You write the class
Specificity General-purpose Domain-specific
Custom data Only a message string Any attributes you want
Catching May catch unrelated errors Precise, targeted handling
Readability raise ValueError(...) raise InsufficientFundsError(...)

How to Create One: Step by Step

1
Name your error: Choose a descriptive name ending in Error (e.g., InvalidEmailError).
2
Inherit from Exception: Write class YourError(Exception) to plug into Python's exception system.
3
Add __init__ (optional): Accept custom parameters and call super().__init__(message).
4
Add __str__ (optional): Customize how the error prints when uncaught.
5
Raise and catch: Use raise YourError(...) and except YourError as e.

Example 1: Simplest Form

# Define the custom exception class InvalidScoreError(Exception): pass # Use it in a function def set_score(score): if score < 0 or score > 100: raise InvalidScoreError(f"Score {score} is out of range") return score

Example 2: Custom Attributes

class InsufficientFundsError(Exception): def __init__(self, balance, amount): self.balance = balance self.amount = amount self.deficit = amount - balance super().__init__( f"Need ${amount}, have ${balance}" )

Example 3: Full Raise / Except Flow

class InvalidEmailError(Exception): def __init__(self, email): self.email = email super().__init__(f"'{email}' is not valid") def register_user(email): if "@" not in email: raise InvalidEmailError(email) print(f"Registered: {email}") try: register_user("not-an-email") except InvalidEmailError as e: print(f"Error: {e}") print(f"Bad email: {e.email}")

Building Exception Hierarchies

You can create a base exception for your application, then derive more specific ones from it. This lets callers catch all your errors or just specific subtypes.

class AppError(Exception): """Base for all app exceptions.""" class DatabaseError(AppError): pass class AuthenticationError(AppError): pass # Catches both DatabaseError and AuthenticationError except AppError: ...

__str__ and __repr__

__str__
User-friendly message shown when the exception is printed or converted to a string.
__repr__
Developer-friendly representation shown in the debugger, useful for logging and reproducing the error.
class TempTooHighError(Exception): def __init__(self, temp, limit): self.temp = temp self.limit = limit super().__init__(f"Temp {temp} exceeds {limit}") def __repr__(self): return f"TempTooHighError({self.temp}, {self.limit})"

When Not to Use Custom Exceptions

Custom exceptions are powerful, but overusing them creates complexity without benefit. Use a built-in when one fits perfectly.

✓ Do use custom
Domain-specific errors: business rules, validation, API constraints that no built-in exception describes well.
✕ Do not use custom
When a built-in fits: wrong type? Use TypeError. Missing file? Use FileNotFoundError. Keep it simple.

Common Mistakes

✕ Inheriting from BaseException
BaseException catches keyboard interrupts and system exits. Always inherit from Exception instead.
✕ Forgetting super().__init__
Without calling the parent constructor, the error message will not display properly in tracebacks.
✕ Vague naming
Names like "MyError" or "CustomError" give no useful information. Be specific: InvalidAgeError, QuotaExceededError.

Quick Reference Summary

Concept Syntax / Detail
Minimal custom exception class MyError(Exception): pass
Custom message super().__init__(msg) in __init__
Custom attributes self.attr = value in __init__
Raising raise MyError("details")
Catching except MyError as e:
Hierarchy base Inherit from Exception, not BaseException
Naming convention End with Error (PascalCase)

Question 1 of 5

Which class should a custom exception always inherit from?

Question 2 of 5

What is the minimum valid definition of a custom exception class?

Question 3 of 5

What does the code print?

Question 4 of 5

Why is calling super().__init__(message) important inside a custom exception's __init__?

Question 5 of 5

Will the except AppError block catch the DatabaseError?