Creating Custom Exceptions in Python
with clear explanations and multiple examples — same format and style:
Creating Custom Exceptions in Python
In Python, you can define your own custom exception classes to represent specific errors in your application.
- Helps create clear, meaningful error types
- Makes your code easier to read, debug, and maintain
- Custom exceptions can carry extra information
Why Create Custom Exceptions?
Reason | Benefit |
---|---|
Represent business logic errors | E.g. InvalidTransactionError |
Provide descriptive names | Easier debugging |
Add extra attributes | More context about errors |
Enable targeted error handling | Catch specific exception types |
How to Create a Custom Exception
Define a new class
Inherit from built-in Exception
(or a subclass)
Optionally, override the __init__
and __str__
methods
class MyCustomError(Exception):
pass
Example 1: Simple Custom Exception
class InvalidAgeError(Exception):
pass
def set_age(age):
if age < 0:
raise InvalidAgeError("Age cannot be negative.")
print("Age set to:", age)
set_age(25)
set_age(-3)
Age set to: 25
InvalidAgeError: Age cannot be negative.
Example 2: Custom Exception with __init__
class ScoreError(Exception):
def __init__(self, score, message="Invalid score."):
self.score = score
self.message = message
super().__init__(self.message)
def set_score(score):
if score > 100:
raise ScoreError(score, "Score cannot exceed 100.")
print("Score set to:", score)
set_score(95)
set_score(120)
Score set to: 95
ScoreError: Score cannot exceed 100.
Example 3: Inheriting from a Subclass of Exception
You can inherit from specific exception types:
class MyFileNotFoundError(FileNotFoundError):
pass
try:
raise MyFileNotFoundError("Custom file not found error.")
except MyFileNotFoundError as e:
print("Caught error:", e)
Caught error: Custom file not found error.
Example 4: Custom Exception with Extra Attributes
class PaymentError(Exception):
def __init__(self, amount, balance):
self.amount = amount
self.balance = balance
super().__init__(f"Cannot process payment of {amount}. Balance is {balance}.")
try:
raise PaymentError(150, 100)
except PaymentError as e:
print(e)
print("Amount:", e.amount)
print("Balance:", e.balance)
Cannot process payment of 150. Balance is 100.
Amount: 150
Balance: 100
Best Practices for Custom Exceptions
Inherit from Exception
or a subclass
Use descriptive names ending with Error
Add helpful error messages
Include extra attributes if needed
Key Points
Use custom exceptions to represent specific application errors
Makes your code self-explanatory and easier to debug
Enables precise exception handling
Use __init__
and extra attributes for advanced use cases
Summary
- Python lets you create custom exceptions by defining new classes
- Inherit from
Exception
- Add extra context with attributes and messages
- Helps you enforce domain-specific rules in your application
Next, we will explore File Handling in Python — how to read from, write to, and work with files using clean and safe coding patterns.