Python Custom Exceptions
Table of Contents
Description
Custom Exceptions let you define your own error types to better describe specific errors in your application.
A Custom Exception Hierarchy organizes your exceptions into parent-child relationships, improving readability and error handling structure.
Error Logging records error messages and exceptions to a file or console, allowing easier debugging and monitoring.
Prerequisites
- Knowledge of:
Python classes and inheritance
Built-in exceptions (Exception, ValueError, etc.)
try-except handling
Basics of file handling and the logging module
Examples
Here's a simple program in Python:
✅ Creating a Basic Custom Exception # Define a basic custom exception by inheriting from Exception class InvalidInputError(Exception): pass def check_input(value): if not isinstance(value, int): # Raise your custom exception raise InvalidInputError("Input must be an integer.") # check_input("abc") ✅ Custom Exception with Constructor class SalaryTooLowError(Exception): def __init__(self, salary, message="Salary is below the minimum threshold."): self.salary = salary self.message = message super().__init__(self.message) def process_salary(salary): if salary < 3000: raise SalaryTooLowError(salary) print("Salary processed:", salary) # process_salary(2500) ✅ Custom Exception Hierarchy # Base exception for application class AppError(Exception): """Base class for other exceptions""" pass # Derived exceptions class DatabaseError(AppError): pass class ValidationError(AppError): pass # Example usage def validate_data(data): if not data: raise ValidationError("Data cannot be empty.") def save_to_db(data): if data == "error": raise DatabaseError("Failed to connect to DB.") # validate_data("") # save_to_db("error") ✅ Logging Exceptions with logging Module import logging # Configure the logging system logging.basicConfig( filename='app.log', # Log to a file named app.log level=logging.ERROR, # Only log ERROR level and above format='%(asctime)s - %(levelname)s - %(message)s' ) try: result = 10 / 0 except ZeroDivisionError as e: logging.error("Exception occurred", exc_info=True) # Logs the full tracebackReal-World Applications
Define clear and descriptive errors in large applications
Hierarchical exception structures in APIs/frameworks
Debugging production issues using logs
Monitoring application health through log aggregation tools (e.g., ELK stack)
Where topic Can Be Applied
Web Development: Raise and handle specific user errors (e.g., form validation)
Banking/Finance: Enforce transaction rules via custom exceptions
Enterprise Software: Large systems use exception hierarchies to manage thousands of error cases
Machine Learning Pipelines: Log model load, preprocess, or training issues
Resources
WatchTopic video source
A comprehensive video
VisitPython pdf
pdf on topic
Interview Questions
Why should we create custom exceptions?
How do you define a custom exception in Python?
What is an exception hierarchy?
What is the advantage of using a base custom exception class?
How do you log exceptions to a file?
What is exc_info=True used for in logging?