Custom
Exceptions
Learn how to define your own exception classes in Python to write cleaner, more descriptive error handling for your programs.
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.
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.
Why Create Custom Exceptions?
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.
Anatomy of a Custom Exception
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
Example 1: Simplest Form
Example 2: Custom Attributes
Example 3: Full Raise / Except Flow
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.
__str__ and __repr__
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.
Common Mistakes
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
Consider this code:
class LowBatteryError(Exception):
def __init__(self, level):
self.level = level
super().__init__(f"Battery at {level}%")
try:
raise LowBatteryError(5)
except LowBatteryError as e:
print(e.level)
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
Consider this hierarchy:
class AppError(Exception): pass
class DatabaseError(AppError): pass
class AuthError(AppError): pass
try:
raise DatabaseError("connection lost")
except AppError:
print("caught!")
Will the except AppError block catch the DatabaseError?