Python Docs
Python Custom Exceptions — Full Cheat Sheet
What Are Custom Exceptions?
Python allows you to create your own exception classes. These help you provide clear, meaningful errors that match your application’s needs.
Why Use Custom Exceptions?
- Make error messages easier to understand
- Structure your code with specific exception types
- Better debugging & maintainability
- Useful for validating API inputs, forms, user data, etc.
Creating a Basic Custom Exception
All custom exceptions must inherit from Python’s built-in Exception class.
class MyError(Exception):
pass
raise MyError("Something went wrong!")Custom Exception with Constructor
You can customize the message using __init__().
class AgeError(Exception):
def __init__(self, message):
self.message = message
age = -5
if age < 0:
raise AgeError("Age cannot be negative")Using Custom Exceptions in Functions
class ValidationError(Exception):
pass
def check_value(x):
if x < 0:
raise ValidationError("Negative values not allowed")
check_value(-2)Multiple Custom Exceptions
You can structure your exceptions in a hierarchy for more control.
class CustomError(Exception):
pass
class ValueTooSmallError(CustomError):
pass
class ValueTooLargeError(CustomError):
pass
def check(num):
if num < 10:
raise ValueTooSmallError("Value is too small")
if num > 100:
raise ValueTooLargeError("Value is too large")
return "Value is acceptable"
check(150)Catching Custom Exceptions
Use try–except just like with built-in exceptions.
try:
raise ValueError("Invalid number")
except ValueError as e:
print("Caught custom error:", e)Best Practices
- Always inherit from
Exception(notBaseException) - Use meaningful names like
LoginErrororAgeError - Do not overuse exceptions—only when necessary
- Group related exceptions under a common base class
Common Use Cases for Custom Exceptions
| Use Case | Example Exception Name |
|---|---|
| Invalid user input | InputError |
| Authentication failure | LoginError |
| API request problems | APIError |
| Invalid format or data | FormatError |
| File validation | FileError |
Summary
- Custom exceptions help in writing clean, understandable error handling.
- They inherit from Python’s built-in
Exceptionclass. - Useful for input validation, API errors, business logic validation, etc.
- Can be organized in hierarchies for better error management.
- Use them with
try–exceptstatements like normal exceptions.