PythonCreating Custom Exceptions

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.

  1. Helps create clear, meaningful error types
  2. Makes your code easier to read, debug, and maintain
  3. Custom exceptions can carry extra information

Why Create Custom Exceptions?

ReasonBenefit
Represent business logic errorsE.g. InvalidTransactionError
Provide descriptive namesEasier debugging
Add extra attributesMore context about errors
Enable targeted error handlingCatch 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

custom_exception_syntax.py
class MyCustomError(Exception):
    pass

Example 1: Simple Custom Exception

example1_simple_custom.py
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)
output.txt
Age set to: 25
InvalidAgeError: Age cannot be negative.

Example 2: Custom Exception with __init__

example2_custom_init.py
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)
output.txt
Score set to: 95
ScoreError: Score cannot exceed 100.

Example 3: Inheriting from a Subclass of Exception

You can inherit from specific exception types:

example3_custom_subclass.py
class MyFileNotFoundError(FileNotFoundError):
    pass
 
try:
    raise MyFileNotFoundError("Custom file not found error.")
except MyFileNotFoundError as e:
    print("Caught error:", e)
output.txt
Caught error: Custom file not found error.

Example 4: Custom Exception with Extra Attributes

example4_custom_attributes.py
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)
output.txt
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.